<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>好卖管家</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
    <!-- 添加ZXing-js库(UMD版本)，用于二维码和条形码的生成与识别 -->
    <script src="https://cdn.jsdelivr.net/npm/@zxing/library@0.20.0/umd/index.min.js"></script>

    <!-- 加载数据存储模块 - 直接通过script标签加载，而不是ES模块 -->
    <script src="./data-storage.js"></script>
    <!-- 加载支付管理模块 -->
    <script src="./data-payment.js"></script>
    <!-- 加载TTS语音功能模块 -->
    <script src="./tts.js"></script>
    <script>
        // 添加全局变量用于跟踪当前支付订单
        let currentPaymentOrderId = null;
        let currentPaymentAmount = null;
        let currentPaymentMethod = null;
        
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#2563eb',
                        secondary: '#10b981',
                        accent: '#f59e0b',
                        danger: '#ef4444',
                        dark: '#1e293b',
                        light: '#f8fafc'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
        
        // 检查是否有待支付的订单
        function checkPendingOrders() {
            if (typeof window.dataStore !== 'undefined') {
                const orders = window.dataStore.orders;
                const pendingOrder = orders.find(order => order.status === 'pending');
                if (pendingOrder) {
                    // 显示继续支付界面
                    showContinuePayment(pendingOrder);
                }
            }
        }
        
        // 在initApp函数中调用checkPendingOrders，避免重复初始化
        
        // 显示继续支付界面
        function showContinuePayment(order) {
            currentPaymentOrderId = order.id;
            currentPaymentAmount = order.totalAmount;
            
            // 显示支付界面
            showPaymentScreen(order.totalAmount);
        }
        
        // 处理支付成功通知
        function handlePaymentReceived(amount, platform) {
            // 检查金额是否匹配当前待支付订单
            if (currentPaymentOrderId && currentPaymentAmount) {
                // 由于浮点数精度问题，我们允许小额差异（例如1分钱以内）
                const amountDiff = Math.abs(parseFloat(amount) - parseFloat(currentPaymentAmount));
                if (amountDiff <= 0.01) {
                    // 更新订单状态为已支付
                    if (typeof dataStorage !== 'undefined') {
                        dataStorage.updateOrderStatus(currentPaymentOrderId, 'paid', platform);
                        
                        // 显示支付成功消息
                        showPaymentSuccess(platform, amount);
                        
                        // 清空当前支付信息
                        currentPaymentOrderId = null;
                        currentPaymentAmount = null;
                        currentPaymentMethod = null;
                        
                        // 隐藏支付界面
                        hidePaymentScreen();
                    }
                } else {
                    // 金额不匹配，显示警告
                    alert(`收到支付通知，但金额(${amount})与订单金额(${currentPaymentAmount})不匹配`);
                }
            }
        }
        
        // 显示支付成功消息
        function showPaymentSuccess(platform, amount) {
            const platformName = platform === 'wechat' ? '微信' : '支付宝';
            alert(`${platformName}支付成功！收到金额：${amount}元`);
            
            // 如果有TTS功能，播放语音提示
            if (typeof ttsManager !== 'undefined') {
                ttsManager.speak(`收到${platformName}付款${amount}元`);
            }
        }
        
        // 修改生成支付二维码的函数
        function generatePaymentQRCode(platform, amount, orderId) {
            if (typeof paymentManager !== 'undefined') {
                // 保存当前支付信息
                currentPaymentOrderId = orderId;
                currentPaymentAmount = amount;
                currentPaymentMethod = platform;
                
                // 生成带金额的支付链接
                const paymentLink = paymentManager.generatePaymentLink(platform, amount);
                if (paymentLink) {
                    // 使用离线库生成二维码
                    return generateOfflineQRCode(paymentLink);
                }
            }
            return null;
        }
        
        // 使用ZXing-js库生成二维码
        function generateOfflineQRCode(paymentLink) {
            try {
                // 检查ZXing库是否存在（适配UMD版本）
                if (typeof ZXing === 'undefined' || (typeof window !== 'undefined' && typeof window.ZXing === 'undefined') || 
                    (typeof ZXing !== 'undefined' && typeof ZXing.BrowserQRCodeSvgWriter === 'undefined') ||
                    (typeof window !== 'undefined' && typeof window.ZXing !== 'undefined' && typeof window.ZXing.BrowserQRCodeSvgWriter === 'undefined')) {
                    console.error('ZXing库未加载，无法生成二维码');
                    // 尝试使用备用方式生成二维码
                    return generateFallbackQRCode(paymentLink);
                }
                
                // 确保使用正确的ZXing实例
                const zxingInstance = typeof window !== 'undefined' && typeof window.ZXing !== 'undefined' ? window.ZXing : ZXing;
                
                // 创建ZXing二维码生成器
                const writer = new zxingInstance.BrowserQRCodeSvgWriter();
                
                // 生成SVG格式的二维码
                const svgElement = writer.write(paymentLink, 240, 240);
                
                // 将SVG转换为Data URL
                const svgString = new XMLSerializer().serializeToString(svgElement);
                const blob = new Blob([svgString], {type: 'image/svg+xml'});
                const url = URL.createObjectURL(blob);
                
                // 创建临时canvas来转换为PNG
                const canvas = document.createElement('canvas');
                canvas.width = 240;
                canvas.height = 240;
                const ctx = canvas.getContext('2d');
                
                const img = new Image();
                img.src = url;
                
                // 返回一个Promise，等待图像加载完成
                return new Promise((resolve) => {
                    img.onload = () => {
                        ctx.drawImage(img, 0, 0, 240, 240);
                        const pngUrl = canvas.toDataURL('image/png');
                        URL.revokeObjectURL(url); // 释放URL对象
                        resolve(pngUrl);
                    };
                    
                    img.onerror = () => {
                        console.error('二维码图像加载失败，使用备用方式');
                        URL.revokeObjectURL(url); // 释放URL对象
                        resolve(generateFallbackQRCode(paymentLink));
                    };
                });
            } catch (error) {
                console.error('生成二维码时出错:', error);
                // 出错时使用备用方式
                return generateFallbackQRCode(paymentLink);
            }
        }
        
        // 备用二维码生成方式（使用canvas手动绘制）
        function generateFallbackQRCode(text) {
            try {
                const canvas = document.createElement('canvas');
                canvas.width = 240;
                canvas.height = 240;
                const ctx = canvas.getContext('2d');
                
                // 填充白色背景
                ctx.fillStyle = '#ffffff';
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                
                // 设置黑色前景
                ctx.fillStyle = '#000000';
                
                // 绘制基本的二维码图案（基于文本生成伪随机图案）
                const cellSize = 8;
                const cellsPerSide = 30;
                
                // 简单的哈希函数将文本转换为图案
                let hash = 0;
                for (let i = 0; i < text.length; i++) {
                    const char = text.charCodeAt(i);
                    hash = ((hash << 5) - hash) + char;
                    hash = hash & hash; // 转换为32位整数
                }
                
                // 设置随机种子
                let seed = hash;
                function random() {
                    const x = Math.sin(seed++) * 10000;
                    return x - Math.floor(x);
                }
                
                // 绘制定位图案（三个角）
                drawPositionPattern(ctx, 3, 3, cellSize);
                drawPositionPattern(ctx, canvas.width - 3 - 7 * cellSize, 3, cellSize);
                drawPositionPattern(ctx, 3, canvas.height - 3 - 7 * cellSize, cellSize);
                
                // 绘制数据区域
                for (let y = 0; y < cellsPerSide; y++) {
                    for (let x = 0; x < cellsPerSide; x++) {
                        // 跳过定位图案区域
                        if ((x >= 0 && x < 10 && y >= 0 && y < 10) ||
                            (x >= cellsPerSide - 10 && y >= 0 && y < 10) ||
                            (x >= 0 && x < 10 && y >= cellsPerSide - 10)) {
                            continue;
                        }
                        
                        // 根据伪随机数决定是否填充
                        if (random() > 0.5) {
                            const px = x * cellSize + 15;
                            const py = y * cellSize + 15;
                            ctx.fillRect(px, py, cellSize - 1, cellSize - 1);
                        }
                    }
                }
                
                return canvas.toDataURL('image/png');
            } catch (error) {
                console.error('备用二维码生成方式也失败:', error);
                return null;
            }
        }
        
        // 绘制二维码定位图案
        function drawPositionPattern(ctx, x, y, cellSize) {
            ctx.fillRect(x, y, 7 * cellSize, 7 * cellSize);
            ctx.fillStyle = '#ffffff';
            ctx.fillRect(x + cellSize, y + cellSize, 5 * cellSize, 5 * cellSize);
            ctx.fillStyle = '#000000';
            ctx.fillRect(x + 2 * cellSize, y + 2 * cellSize, 3 * cellSize, 3 * cellSize);
        }
        
        // 创建订单
        function createOrder() {
            if (typeof dataStorage !== 'undefined') {
                try {
                    const order = dataStorage.createOrder();
                    if (order) {
                        // 订单创建成功，显示支付界面
                        showPaymentScreen(order.totalAmount, order.id);
                        return order;
                    }
                } catch (error) {
                    alert('创建订单失败: ' + error.message);
                }
            }
            return null;
        }
        
        // 显示支付界面
        function showPaymentScreen(amount, orderId) {
            // 这里应该显示支付界面，包含二维码等
            console.log('显示支付界面，金额：' + amount + '，订单ID：' + orderId);
        }
        
        // 隐藏支付界面
        function hidePaymentScreen() {
            // 这里应该隐藏支付界面
            console.log('隐藏支付界面');
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .scan-box {
                border: 2px solid theme('colors.secondary');
                box-shadow: 0 0 0 1000px rgba(0, 0, 0, 0.5);
            }
            .btn-primary {
                @apply bg-primary text-white py-3 px-6 rounded-lg shadow-md hover:bg-primary/90 transition-all duration-300 active:scale-95;
            }
            .btn-secondary {
                @apply bg-secondary text-white py-3 px-6 rounded-lg shadow-md hover:bg-secondary/90 transition-all duration-300 active:scale-95;
            }
            .btn-accent {
                @apply bg-accent text-white py-3 px-6 rounded-lg shadow-md hover:bg-accent/90 transition-all duration-300 active:scale-95;
            }
            .btn-danger {
                @apply bg-danger text-white py-3 px-6 rounded-lg shadow-md hover:bg-danger/90 transition-all duration-300 active:scale-95;
            }
            .card {
                @apply bg-white rounded-xl shadow-lg p-5 mb-5 transition-all duration-300 hover:shadow-xl;
            }
            /* 开关组件样式 */
            .switch {
                position: relative;
                display: inline-block;
                width: 60px;
                height: 34px;
            }
            .switch input {
                opacity: 0;
                width: 0;
                height: 0;
            }
            .slider {
                position: absolute;
                cursor: pointer;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background-color: #ccc;
                transition: .4s;
                border-radius: 34px;
            }
            .slider:before {
                position: absolute;
                content: "";
                height: 26px;
                width: 26px;
                left: 4px;
                bottom: 4px;
                background-color: white;
                transition: .4s;
                border-radius: 50%;
            }
            input:checked + .slider {
                background-color: #2196F3;
            }
            input:focus + .slider {
                box-shadow: 0 0 1px #2196F3;
            }
            input:checked + .slider:before {
                transform: translateX(26px);
            }

            /* 同步功能额外样式 */
            .btn-primary:hover,
            .btn-secondary:hover {
                transform: translateY(-1px);
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            }
            .btn-primary:active,
            .btn-secondary:active {
                transform: translateY(0);
                box-shadow: 0 2px 3px rgba(0, 0, 0, 0.1);
            }
            /* 同步历史记录滚动条样式 */
            .max-h-96::-webkit-scrollbar {
                width: 6px;
            }
            .max-h-96::-webkit-scrollbar-track {
                background: #f1f1f1;
                border-radius: 3px;
            }
            .max-h-96::-webkit-scrollbar-thumb {
                background: #ccc;
                border-radius: 3px;
            }
            .max-h-96::-webkit-scrollbar-thumb:hover {
                background: #aaa;
            }
        }    </style>
    </head>
    <body class="bg-gray-100 min-h-screen font-sans text-dark">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-md fixed top-0 left-0 right-0 z-50">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
            <h1 class="text-xl font-bold text-primary" id="header-title">好卖管家</h1>
            <button id="menu-btn" class="text-dark p-2">
                <i class="fa fa-bars text-xl"></i>
            </button>
        </div>
    </header>

    <!-- 侧边菜单 -->
    <div id="sidebar" class="fixed top-0 right-0 h-full w-64 bg-white shadow-2xl transform translate-x-full transition-transform duration-300 z-50">
        <div class="p-4 border-b flex justify-between items-center">
            <h2 class="font-bold text-lg">菜单</h2>
            <button id="close-menu" class="p-2">
                <i class="fa fa-times text-xl"></i>
            </button>
        </div>
        <nav class="p-4">
            <ul class="space-y-4">
                <li>
                    <button class="menu-item w-full text-left flex items-center p-2 hover:bg-gray-100 rounded-lg" data-target="home">
                        <i class="fa fa-home w-6 mr-2"></i> 首页
                    </button>
                </li>
                <li>
                    <button class="menu-item w-full text-left flex items-center p-2 hover:bg-gray-100 rounded-lg" data-target="scan-product">
                        <i class="fa fa-barcode w-6 mr-2"></i> 扫描商品
                    </button>
                </li>
                <li>
                    <button class="menu-item w-full text-left flex items-center p-2 hover:bg-gray-100 rounded-lg" data-target="product-management">
                        <i class="fa fa-cubes w-6 mr-2"></i> 商品管理
                    </button>
                </li>
                <li>
                    <button class="menu-item w-full text-left flex items-center p-2 hover:bg-gray-100 rounded-lg" data-target="checkout">
                        <i class="fa fa-shopping-cart w-6 mr-2"></i> 收银台
                    </button>
                </li>
                <li>
                    <button class="menu-item w-full text-left flex items-center p-2 hover:bg-gray-100 rounded-lg" data-target="statistics">
                        <i class="fa fa-bar-chart w-6 mr-2"></i> 销售统计
                    </button>
                </li>
                <li>
                    <button class="menu-item w-full text-left flex items-center p-2 hover:bg-gray-100 rounded-lg" data-target="data-management">
                        <i class="fa fa-database w-6 mr-2"></i> 数据管理
                    </button>
                </li>
                <li>
                    <button class="menu-item w-full text-left flex items-center p-2 hover:bg-gray-100 rounded-lg" data-target="account-management">
                        <i class="fa fa-user w-6 mr-2"></i> 我的
                    </button>
                </li>
            </ul>
        </nav>
    </div>

    <!-- 主内容区 -->
    <main class="container mx-auto px-4 pt-20 pb-20">
        <!-- 首页 -->
        <section id="home" class="page active">
            <div class="text-center py-8">
                <h2 class="text-2xl font-bold mb-2">欢迎使用好卖管家</h2>
                <p class="text-gray-600 mb-8">用手机轻松管理商品和收款</p>
                
                <div class="grid grid-cols-2 gap-4 mb-8">
                    <button class="card flex flex-col items-center justify-center p-6" onclick="navigateTo('scan-product')">
                        <i class="fa fa-barcode text-4xl text-primary mb-3"></i>
                        <span class="font-medium">扫描商品</span>
                    </button>
                    <button class="card flex flex-col items-center justify-center p-6" onclick="navigateTo('checkout')">
                        <i class="fa fa-shopping-cart text-4xl text-secondary mb-3"></i>
                        <span class="font-medium">收银台</span>
                    </button>
                    <button class="card flex flex-col items-center justify-center p-6" onclick="navigateTo('product-management')">
                        <i class="fa fa-cubes text-4xl text-accent mb-3"></i>
                        <span class="font-medium">商品管理</span>
                    </button>
                    <button class="card flex flex-col items-center justify-center p-6" onclick="navigateTo('statistics')">
                        <i class="fa fa-bar-chart text-4xl text-primary mb-3"></i>
                        <span class="font-medium">销售统计</span>
                    </button>
                </div>
                
                <div class="card">
                    <h3 class="text-lg font-semibold mb-4">今日概览</h3>
                    <div class="grid grid-cols-2 gap-4">
                        <div class="bg-blue-50 p-4 rounded-lg">
                            <p class="text-gray-600 text-sm">今日销售额</p>
                            <p class="text-2xl font-bold text-primary" id="today-sales">¥0.00</p>
                        </div>
                        <div class="bg-green-50 p-4 rounded-lg">
                            <p class="text-gray-600 text-sm">今日订单数</p>
                            <p class="text-2xl font-bold text-secondary" id="today-orders">0</p>
                        </div>
                        <div class="bg-orange-50 p-4 rounded-lg">
                            <p class="text-gray-600 text-sm">今日商品数</p>
                            <p class="text-2xl font-bold text-accent" id="total-products">0</p>
                        </div>
                        <div class="bg-purple-50 p-4 rounded-lg">
                            <p class="text-gray-600 text-sm">库存预警</p>
                            <p class="text-2xl font-bold text-purple-600" id="stock-alerts">0</p>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- 扫描商品页面 -->
        <section id="scan-product" class="page hidden">
            <div class="text-center mb-6">
                <h2 class="text-2xl font-bold mb-2">扫描商品</h2>
                <p class="text-gray-600">扫描条形码添加或更新商品信息</p>
            </div>
            
            <div class="card">
                <div class="mb-6">
                    <div class="relative aspect-video bg-dark rounded-lg overflow-hidden">
                        <video id="scan-preview" class="w-full h-full object-cover"></video>
                        <div class="absolute inset-0 flex items-center justify-center">
                            <div class="scan-box w-3/4 aspect-video flex items-center justify-center relative">
                                <!-- 添加四角装饰元素 -->
                                <div class="absolute top-0 left-0 w-8 h-8 border-t-4 border-l-4 border-secondary"></div>
                                <div class="absolute top-0 right-0 w-8 h-8 border-t-4 border-r-4 border-secondary"></div>
                                <div class="absolute bottom-0 left-0 w-8 h-8 border-b-4 border-l-4 border-secondary"></div>
                                <div class="absolute bottom-0 right-0 w-8 h-8 border-b-4 border-r-4 border-secondary"></div>
                                <!-- 添加扫描线 -->
                                <div class="w-full h-1 bg-secondary animate-pulse"></div>
                            </div>
                        </div>
                    </div>
                    <!-- 将开始扫描按钮移到视频外部，使其更突出 -->
                    <div class="flex justify-center mt-4">
                        <button id="start-scan" class="bg-secondary text-white px-6 py-3 rounded-full shadow-lg hover:bg-secondary/90 transition-all transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-secondary focus:ring-offset-2">
                            <i class="fa fa-play mr-2"></i> 开始扫描
                        </button>
                    </div>
                </div>
                
                <div id="product-form" class="hidden">
                    <h3 class="text-lg font-semibold mb-4">商品信息</h3>
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">条形码</label>
                            <input type="text" id="product-barcode" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary" placeholder="输入或扫描条形码">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">商品名称</label>
                            <input type="text" id="product-name" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary" placeholder="输入商品名称">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">商品分类</label>
                            <select id="product-category" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary appearance-none bg-white md:bg-transparent md:appearance-auto">
                                <option value="">请选择分类</option>
                                <option value="烟">烟</option>
                                <option value="酒">酒</option>
                                <option value="食品">食品</option>
                                <option value="饮料">饮料</option>
                                <option value="日用品">日用品</option>
                                <option value="其他">其他</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">进货价格 (¥)</label>
                            <input type="number" step="0.01" min="0" id="product-cost" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary" placeholder="0.00">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">零售价格 (¥)</label>
                            <input type="number" step="0.01" min="0" id="product-price" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary" placeholder="0.00">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">库存数量</label>
                            <input type="number" min="0" id="product-stock" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary" placeholder="0">
                        </div>
                        <div class="flex gap-4 pt-2">
                            <button id="save-product" class="btn-secondary flex-1">保存商品</button>
                            <button id="cancel-product" class="btn-danger flex-1">取消</button>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- 商品管理页面 -->
        <section id="product-management" class="page hidden">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-2xl font-bold">商品管理</h2>
                <button onclick="addNewProduct()" class="bg-primary text-white p-2 rounded-lg shadow">
                    <i class="fa fa-plus mr-1"></i> 添加
                </button>
            </div>
            
            <div class="card mb-4">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="relative">
                        <input type="text" id="product-search" placeholder="搜索商品名称或条形码..." class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary">
                        <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                    </div>
                    <div>
                        <select id="product-category-filter" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary appearance-none bg-white md:bg-transparent md:appearance-auto">
                            <option value="">全部分类</option>
                            <option value="烟">烟</option>
                            <option value="酒">酒</option>
                            <option value="食品">食品</option>
                            <option value="饮料">饮料</option>
                            <option value="日用品">日用品</option>
                            <option value="其他">其他</option>
                        </select>
                    </div>
                </div>
            </div>
            
            <div class="card">
                <h3 class="text-lg font-semibold mb-4">商品列表</h3>
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead>
                            <tr>
                                <th class="px-3 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">名称</th>
                                <th class="px-3 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">零售价</th>
                                <th class="px-3 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">库存</th>
                                <th class="px-3 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                            </tr>
                        </thead>
                        <tbody id="product-list" class="bg-white divide-y divide-gray-200">
                            <!-- 商品列表将通过JS动态生成 -->
                            <tr>
                                <td colspan="7" class="px-3 py-8 text-center text-gray-500">暂无商品数据</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </section>

        <!-- 收银台页面 -->
        <section id="checkout" class="page hidden">
            <div class="text-center mb-6">
                <h2 class="text-2xl font-bold mb-2">收银台</h2>
                <p class="text-gray-600">扫描商品条形码进行结算</p>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                <div class="md:col-span-2">
                    <div class="card h-full">
                        <div class="mb-6">
                            <div class="relative aspect-video bg-dark rounded-lg overflow-hidden">
                                <video id="checkout-preview" class="w-full h-full object-cover"></video>
                                <div class="absolute inset-0 flex items-center justify-center">
                                    <div class="scan-box w-3/4 aspect-video flex items-center justify-center relative">
                                        <!-- 添加四角装饰元素 -->
                                        <div class="absolute top-0 left-0 w-8 h-8 border-t-4 border-l-4 border-secondary"></div>
                                        <div class="absolute top-0 right-0 w-8 h-8 border-t-4 border-r-4 border-secondary"></div>
                                        <div class="absolute bottom-0 left-0 w-8 h-8 border-b-4 border-l-4 border-secondary"></div>
                                        <div class="absolute bottom-0 right-0 w-8 h-8 border-b-4 border-r-4 border-secondary"></div>
                                        <!-- 添加扫描线 -->
                                        <div class="w-full h-1 bg-secondary animate-pulse"></div>
                                    </div>
                                </div>
                            </div>
                            <!-- 将开始扫描按钮移到视频外部，使其更突出 -->
                            <div class="flex justify-center mt-4">
                                <button id="start-checkout-scan" class="bg-secondary text-white px-6 py-3 rounded-full shadow-lg hover:bg-secondary/90 transition-all transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-secondary focus:ring-offset-2">
                                    <i class="fa fa-play mr-2"></i> 开始扫描
                                </button>
                            </div>
                        </div>
                        
                        <h3 class="text-lg font-semibold mb-3">购物车</h3>
                        <div id="cart-items" class="max-h-60 overflow-y-auto mb-4 space-y-2">
                            <!-- 购物车商品将通过JS动态生成 -->
                            <div class="text-center text-gray-500 py-6">购物车为空</div>
                        </div>
                        
                        <div class="border-t pt-3 mt-3">
                            <div class="flex justify-between mb-2">
                                <span>商品总数:</span>
                                <span id="total-items" class="font-semibold">0</span>
                            </div>
                            <div class="flex justify-between text-lg font-bold">
                                <span>总计:</span>
                                <span id="total-amount" class="text-primary">¥0.00</span>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div>
                    <div class="card h-full">
                        <h3 class="text-lg font-semibold mb-4">结算操作</h3>
                        
                        <div class="space-y-4">
                            <button id="clear-cart" class="btn-danger w-full">
                                <i class="fa fa-trash mr-1"></i> 清空购物车
                            </button>
                            
                            <!-- 简化的支付操作区域 -->
                            <div class="space-y-2">
                                <!-- 微信收款码 -->
                                <button id="wechat-qr-btn" class="w-full py-3 px-4 flex items-center justify-between bg-green-50 text-green-700 border border-green-200 rounded-lg hover:bg-green-100 transition">
                                    <div class="flex items-center">
                                        <i class="fa fa-weixin text-2xl mr-2"></i>
                                        <span>微信收款</span>
                                    </div>
                                    <i class="fa fa-angle-right text-gray-400"></i>
                                </button>
                                
                                <!-- 支付宝收款码 -->
                                <button id="alipay-qr-btn" class="w-full py-3 px-4 flex items-center justify-between bg-blue-50 text-blue-700 border border-blue-200 rounded-lg hover:bg-blue-100 transition">
                                    <div class="flex items-center">
                                        <i class="fa fa-credit-card text-2xl mr-2"></i>
                                        <span>支付宝收款</span>
                                    </div>
                                    <i class="fa fa-angle-right text-gray-400"></i>
                                </button>
                                
                                <!-- 扫描付款码 -->
                                <button id="scan-payment-btn" class="w-full py-3 px-4 flex items-center justify-between bg-purple-50 text-purple-700 border border-purple-200 rounded-lg hover:bg-purple-100 transition">
                                    <div class="flex items-center">
                                        <i class="fa fa-camera text-2xl mr-2"></i>
                                        <span>扫描付款码</span>
                                    </div>
                                    <i class="fa fa-angle-right text-gray-400"></i>
                                </button>
                            </div>
                            
                            <!-- 收款码展示区域 -->
                            <div id="payment-qr-display" class="hidden text-center py-4">
                                <div class="flex justify-between items-center mb-4">
                                    <button id="back-to-payment" class="text-gray-500 hover:text-gray-700">
                                        <i class="fa fa-arrow-left mr-1"></i> 返回
                                    </button>
                                    <h4 id="payment-platform-name" class="font-medium">微信收款</h4>
                                    <div class="w-20"></div> <!-- 占位元素保持居中 -->
                                </div>
                                <p id="payment-qr-amount" class="text-xl font-bold text-primary mb-4">¥0.00</p>
                                <div class="bg-white p-4 inline-block rounded-lg mb-4 shadow-md">
                                    <img id="payment-qr-image" class="w-64 h-64 mx-auto" src="" alt="收款码">
                                </div>
                                <button id="confirm-qr-payment" class="btn-secondary w-full">确认收款</button>
                            </div>
                            
                            <div id="scan-payment" class="hidden">
                                <h4 class="font-medium mb-3">扫描客户付款码</h4>
                                <div class="relative aspect-square bg-dark rounded-lg overflow-hidden mb-3">
                                    <video id="payment-preview" class="w-full h-full object-cover"></video>
                                </div>
                                <button id="start-payment-scan" class="btn-secondary w-full">
                                    <i class="fa fa-play mr-1"></i> 开始扫描
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- 销售统计页面 -->
        <section id="statistics" class="page hidden">
            <div class="text-center mb-6">
                <h2 class="text-2xl font-bold mb-2">销售统计</h2>
                <p class="text-gray-600">查看销售数据和趋势</p>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                <div class="card">
                    <h3 class="text-lg font-semibold mb-4">销售额趋势</h3>
                    <div class="aspect-video">
                        <canvas id="sales-chart"></canvas>
                    </div>
                </div>
                
                <div class="card">
                    <h3 class="text-lg font-semibold mb-4">商品销售排行</h3>
                    <div class="aspect-video">
                        <canvas id="products-chart"></canvas>
                    </div>
                </div>
            </div>
            
            <div class="card">
                <h3 class="text-lg font-semibold mb-4">订单详情</h3>
                <!-- 大屏幕表格布局 -->
                <div class="hidden md:block overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead>
                            <tr>
                                <th class="px-3 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">订单号</th>
                                <th class="px-3 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">日期</th>
                                <th class="px-3 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">商品数</th>
                                <th class="px-3 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">金额</th>
                                <th class="px-3 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">支付状态</th>
                            </tr>
                        </thead>
                        <tbody id="recent-orders-table" class="bg-white divide-y divide-gray-200">
                            <!-- 最近订单表格将通过JS动态生成 -->
                            <tr>
                                <td colspan="5" class="px-3 py-8 text-center text-gray-500">暂无订单数据</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                
                <!-- 移动端卡片布局 -->
                <div class="md:hidden" id="recent-orders-cards">
                    <!-- 最近订单卡片将通过JS动态生成 -->
                    <div class="text-center py-8 text-gray-500">暂无订单数据</div>
                </div>
            </div>
        </section>

        <!-- 数据管理页面 -->
        <section id="data-management" class="page hidden">
            <div class="text-center mb-6">
                <h2 class="text-2xl font-bold mb-2">数据管理</h2>
                <p class="text-gray-600">导出和管理您的销售数据</p>
            </div>
            
            <div class="card mb-6">
                <h3 class="text-lg font-semibold mb-4">数据导出</h3>
                <div class="space-y-4">
                    <button id="export-products" class="btn-primary w-full flex items-center justify-center">
                        <i class="fa fa-download mr-2"></i> 导出商品数据
                    </button>
                    <button id="export-orders" class="btn-primary w-full flex items-center justify-center">
                        <i class="fa fa-download mr-2"></i> 导出订单数据
                    </button>
                    <div class="mt-4 p-3 bg-blue-50 rounded-lg">
                        <p class="text-sm text-blue-700"><i class="fa fa-info-circle mr-1"></i> 数据将导出为CSV格式，可使用Excel等工具打开</p>
                    </div>
                </div>
            </div>
            
            <div class="card">
                <h3 class="text-lg font-semibold mb-4">数据清理</h3>
                <div class="space-y-4">
                    <button id="clear-all-data" class="btn-danger w-full flex items-center justify-center">
                        <i class="fa fa-trash mr-2"></i> 清除所有数据
                    </button>
                    <div class="mt-4 p-3 bg-red-50 rounded-lg">
                        <p class="text-sm text-red-700"><i class="fa fa-exclamation-triangle mr-1"></i> 警告：此操作将删除所有商品和订单数据，请谨慎操作！</p>
                    </div>
                </div>
            </div>
        </section>
        
        <!-- 我的页面 -->
        <section id="account-management" class="page hidden">
            <div class="text-center mb-6">
                <h2 class="text-2xl font-bold mb-2">我的</h2>
                <p class="text-gray-600">账户和设置管理</p>
            </div>
            
            <!-- 用户认证区域 -->
            <div id="auth-status" class="card mb-6">
                <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 rounded-full bg-primary/20 flex items-center justify-center">
                            <i id="auth-icon" class="fa fa-user-circle text-primary text-xl"></i>
                        </div>
                        <div>
                            <h3 class="text-lg font-semibold text-gray-800">账户</h3>
                            <p id="current-user" class="text-gray-600">未登录</p>
                        </div>
                    </div>
                    <div id="auth-actions" class="flex space-x-3 w-full md:w-auto">
                        <button id="login-btn" class="btn-primary px-4 py-2 rounded-lg hover:shadow-md transition-all transform hover:-translate-y-0.5 flex-1 md:flex-none">
                            <i class="fa fa-sign-in-alt mr-1"></i> 登录
                        </button>
                        <button id="register-btn" class="btn-secondary px-4 py-2 rounded-lg hover:shadow-md transition-all transform hover:-translate-y-0.5 flex-1 md:flex-none">
                            <i class="fa fa-user-plus mr-1"></i> 注册
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- 商户认证 -->
            <div class="card mb-6">
                <h3 class="text-lg font-semibold mb-4">商户认证</h3>
                <div id="merchant-verification" class="space-y-4">
                    <div class="flex justify-between items-center">
                        <span>认证状态</span>
                        <span id="verification-status" class="text-danger">未认证</span>
                    </div>
                    <button id="verify-merchant-btn" class="btn-primary w-full">
                        <i class="fa fa-id-card mr-1"></i> 进行商户认证
                    </button>
                </div>
            </div>
            
            <!-- 收款码设置 -->
            <div class="card mb-6">
                <h3 class="text-lg font-semibold mb-4">收款设置</h3>
                
                <!-- 微信收款码设置 -->
                <div class="mb-6">
                    <div class="flex items-center justify-between mb-3">
                        <h4 class="font-medium">微信收款</h4>
                        <label class="relative inline-flex items-center cursor-pointer">
                            <input type="checkbox" id="wechat-enabled" class="sr-only peer">
                            <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-primary rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                        </label>
                    </div>
                    <div id="wechat-config" class="space-y-3">
                        <div>
                            <label class="block text-gray-700 mb-2">微信收款码图片</label>
                            <input type="file" id="wechat-qr-image" accept="image/*" class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                            <div id="wechat-image-preview" class="mt-2 hidden">
                                <img id="wechat-qr-preview" class="max-w-xs mx-auto" src="" alt="微信收款码">
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 支付宝收款码设置 -->
                <div>
                    <div class="flex items-center justify-between mb-3">
                        <h4 class="font-medium">支付宝收款</h4>
                        <label class="relative inline-flex items-center cursor-pointer">
                            <input type="checkbox" id="alipay-enabled" class="sr-only peer">
                            <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-primary rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                        </label>
                    </div>
                    <div id="alipay-config" class="space-y-3">
                        <div>
                            <label class="block text-gray-700 mb-2">支付宝收款码图片</label>
                            <input type="file" id="alipay-qr-image" accept="image/*" class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                            <div id="alipay-image-preview" class="mt-2 hidden">
                                <img id="alipay-qr-preview" class="max-w-xs mx-auto" src="" alt="支付宝收款码">
                            </div>
                        </div>
                    </div>
                </div>
                
                <button id="save-payment-config" class="btn-primary w-full mt-4">
                    <i class="fa fa-save mr-1"></i> 保存支付配置
                </button>
            </div>
            
            <!-- 支付处理中心 - 默认隐藏 -->
            <div id="payment-processing-center" class="card mb-6 hidden">
                <h3 class="text-lg font-semibold mb-4">选择收款方式</h3>
                <div class="space-y-6">
                    
                    <!-- 通用金额输入 -->
                    <div>
                        <label class="block text-gray-700 mb-2">交易金额</label>
                        <input type="number" id="transaction-amount" class="w-full px-3 py-2 border border-gray-300 rounded-lg" placeholder="请输入交易金额" min="0" step="0.01">
                    </div>
                    
                    <!-- 支付方式选择 -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <!-- 动态收款码 -->
                        <div class="border rounded-lg p-4 bg-gray-50 hover:shadow-md transition-shadow">
                            <h4 class="text-md font-medium mb-3 flex items-center">
                                <i class="fa fa-qrcode text-primary mr-2"></i> 展示收款码
                            </h4>
                            <div class="space-y-3">
                                <div class="text-center">
                                    <div id="payment-qrcode" class="w-36 h-36 mx-auto mb-3 bg-white p-2"></div>
                                    <p id="qrcode-message" class="text-gray-600 text-sm">请输入金额并选择平台</p>
                                </div>
                                <div>
                                    <select id="payment-platform" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm">
                                        <option value="wechat">微信</option>
                                        <option value="alipay">支付宝</option>
                                    </select>
                                </div>
                                <button id="generate-qrcode-btn" class="btn-secondary w-full text-sm py-1">
                                    生成收款码
                                </button>
                            </div>
                        </div>
                        
                        <!-- 付款码扫描 -->
                        <div class="border rounded-lg p-4 bg-gray-50 hover:shadow-md transition-shadow">
                            <h4 class="text-md font-medium mb-3 flex items-center">
                                <i class="fa fa-camera text-primary mr-2"></i> 扫描付款码
                            </h4>
                            <div class="space-y-3">
                                <div class="aspect-square bg-gray-100 rounded flex items-center justify-center mb-3">
                                    <i class="fa fa-camera text-3xl text-gray-400"></i>
                                </div>
                                <button id="scan-payment-btn" class="btn-primary w-full py-1">
                                    扫描客户付款码
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 数据库同步 -->
            <div class="card mb-6">
                <h3 class="text-lg font-semibold mb-4">多设备数据同步</h3>
                <div class="space-y-5">
                    <!-- 同步状态 -->
                    <div class="flex flex-col md:flex-row justify-between items-start md:items-center p-3 bg-white bg-opacity-60 rounded-lg">
                        <div class="flex items-center gap-2 mb-2 md:mb-0">
                            <i class="fa fa-server text-primary"></i>
                            <span class="font-medium">同步状态</span>
                        </div>
                        <div class="flex items-center gap-2">
                            <span id="sync-status" class="text-gray-600 font-semibold">未同步</span>
                            <span id="last-sync-time" class="text-sm text-gray-500">(从未同步)</span>
                        </div>
                    </div>
                    
                    <!-- 同步操作 -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <button id="generate-sync-code-btn" class="btn-secondary px-4 py-3 rounded-lg hover:shadow-md transition-all transform hover:-translate-y-0.5 flex items-center justify-center gap-2">
                            <i class="fa fa-sync-alt text-lg"></i>
                            <span>生成同步码</span>
                        </button>
                        <button id="scan-sync-code-btn" class="btn-primary px-4 py-3 rounded-lg hover:shadow-md transition-all transform hover:-translate-y-0.5 flex items-center justify-center gap-2">
                            <i class="fa fa-qrcode text-lg"></i>
                            <span>扫描同步码</span>
                        </button>
                    </div>
                    
                    <!-- 同步选项 -->
                    <div class="bg-white bg-opacity-60 p-4 rounded-lg">
                        <h4 class="font-medium mb-3 flex items-center gap-2">
                            <i class="fa fa-cog text-primary"></i>
                            同步选项
                        </h4>
                        <div class="space-y-3">
                            <label class="flex items-center justify-between cursor-pointer">
                                <span>自动同步数据</span>
                                <label class="relative inline-flex items-center cursor-pointer">
                                    <input type="checkbox" id="auto-sync-toggle" class="sr-only peer">
                                    <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-primary rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                                </label>
                            </label>
                                <label class="flex items-center justify-between cursor-pointer">
                                    <span>同步商品数据</span>
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" id="sync-products-toggle" class="sr-only peer" checked>
                                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-primary rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                                    </label>
                                </label>
                                <label class="flex items-center justify-between cursor-pointer">
                                    <span>同步订单数据</span>
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" id="sync-orders-toggle" class="sr-only peer" checked>
                                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-primary rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                                    </label>
                                </label>
                            </div>
                            
                            <button id="view-sync-history-btn" class="text-primary hover:text-primary-dark text-sm mt-4 flex items-center gap-1">
                                <i class="fa fa-history"></i>
                                查看同步历史
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </main>

    <!-- 底部导航栏 -->
    <footer class="fixed bottom-0 left-0 right-0 bg-white shadow-lg py-2 px-4 md:hidden">
        <div class="grid grid-cols-5 gap-1">
            <button class="footer-item flex flex-col items-center justify-center py-1" data-target="home">
                <i class="fa fa-home text-lg"></i>
                <span class="text-xs mt-1">首页</span>
            </button> 
            <button class="footer-item flex flex-col items-center justify-center py-1" data-target="checkout">
                <i class="fa fa-shopping-cart text-lg"></i>
                <span class="text-xs mt-1">收银</span>
            </button>
            <button class="footer-item flex flex-col items-center justify-center py-1" data-target="product-management">
                <i class="fa fa-cubes text-lg"></i>
                <span class="text-xs mt-1">商品</span>
            </button>
            <button class="footer-item flex flex-col items-center justify-center py-1" data-target="statistics">
                <i class="fa fa-bar-chart text-lg"></i>
                <span class="text-xs mt-1">统计</span>
            </button>
            <button class="footer-item flex flex-col items-center justify-center py-1" data-target="account-management">
                <i class="fa fa-user text-lg"></i>
                <span class="text-xs mt-1">我的</span>
            </button>
        </div>
    </footer>

    <!-- 通知提示框 -->
        <div id="toast" class="fixed bottom-20 left-1/2 transform -translate-x-1/2 px-6 py-3 rounded-lg shadow-lg opacity-0 transition-opacity duration-300 z-50 font-medium"></div>

        <!-- 订单详情模态框 -->
        <div id="order-detail-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
            <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
                <div class="p-4 border-b flex justify-between items-center">
                    <h3 class="text-xl font-bold" id="modal-order-id">订单详情</h3>
                    <button id="close-modal" class="text-gray-500 hover:text-gray-700">
                        <i class="fa fa-times text-xl"></i>
                    </button>
                </div>
                <div class="p-4">
                    <div class="grid grid-cols-2 gap-4 mb-4">
                        <div>
                            <p class="text-sm text-gray-500">下单时间</p>
                            <p class="font-medium" id="modal-order-date"></p>
                        </div>
                        <div>                
                        <p class="text-sm text-gray-500">支付状态</p>                
                        <p id="modal-order-status" class="font-medium text-green-600">已支付</p>                
                    </div>
                    </div>
                    
                    <h4 class="font-semibold mb-2">商品列表</h4>
                    <div id="modal-order-items" class="space-y-2 mb-4">
                        <!-- 订单商品列表将动态生成 -->
                    </div>
                    
                    <div class="border-t pt-4 mt-4">
                        <div class="flex justify-between mb-2">
                            <span>商品总数:</span>
                            <span id="modal-total-items" class="font-semibold"></span>
                        </div>
                        <div class="flex justify-between text-lg font-bold">
                            <span>订单金额:</span>
                            <span id="modal-total-amount" class="text-primary"></span>
                        </div>
                        
                        <!-- 确认收款按钮，仅在待支付状态显示 -->
                        <div class="mt-4 text-center" id="confirm-payment-container">
                            <button id="confirm-payment-btn" class="bg-primary hover:bg-primary-dark text-white px-6 py-2 rounded-lg transition-colors duration-200 font-medium">
                                确认收款
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    <script>
        // 使用从模块导入的dataStorage对象
        const dataStore = window.dataStore;

        // 页面导航功能
        function navigateTo(pageId) {
            // 隐藏所有页面
            document.querySelectorAll('.page').forEach(page => {
                page.classList.add('hidden');
                page.classList.remove('active');
            });
            
            // 显示目标页面
            const targetPage = document.getElementById(pageId);
            targetPage.classList.remove('hidden');
            targetPage.classList.add('active');
            
            // 更新标题
            const pageTitles = {
                'home': '好卖管家',
                'scan-product': '扫描商品',
                'product-management': '商品管理',
                'checkout': '收银台',
                'statistics': '销售统计',
                'data-management': '数据管理',
                'account-management': '我的'
            };
            document.getElementById('header-title').textContent = pageTitles[pageId] || '好卖管家';
            
            // 更新菜单选中状态
            document.querySelectorAll('.menu-item').forEach(btn => {
                if (btn.dataset.target === pageId) {
                    btn.classList.add('bg-gray-100', 'font-medium');
                } else {
                    btn.classList.remove('bg-gray-100', 'font-medium');
                }
            });
            
            // 更新底部导航选中状态
            document.querySelectorAll('.footer-item').forEach(btn => {
                if (btn.dataset.target === pageId) {
                    btn.classList.add('text-primary', 'font-medium');
                } else {
                    btn.classList.remove('text-primary', 'font-medium');
                }
            });
            
            // 关闭侧边菜单
            document.getElementById('sidebar').classList.add('translate-x-full');
            
            // 如果是统计页面，更新图表
            if (pageId === 'statistics') {
                updateCharts();
            }
            
            // 如果是商品管理页面，刷新商品列表
            if (pageId === 'product-management') {
                renderProductList();
            }
            
            // 如果是首页，更新概览数据
            if (pageId === 'home') {
                updateHomeOverview();
            }
        }

        // 显示通知提示
        function showToast(message, type = 'success', duration = 3000) {
            const toast = document.getElementById('toast');
            toast.textContent = message;
            
            // 移除之前的类型样式
            toast.classList.remove('bg-success', 'bg-info', 'bg-danger', 'bg-warning');
            
            // 根据类型添加相应的背景色
            switch (type) {
                case 'success':
                    toast.classList.add('bg-success');
                    break;
                case 'info':
                    toast.classList.add('bg-info');
                    break;
                case 'error':
                    toast.classList.add('bg-danger');
                    break;
                case 'warning':
                    toast.classList.add('bg-warning');
                    toast.classList.add('text-dark');
                    break;
                default:
                    toast.classList.add('bg-success');
            }
            
            toast.classList.remove('opacity-0');
            toast.classList.add('opacity-100');
            
            setTimeout(() => {
                toast.classList.remove('opacity-100');
                toast.classList.add('opacity-0');
            }, duration);
        }
        
        // 显示模态框
        function showModal(title, content) {
            // 检查是否已存在模态框，如果有则移除
            const existingModal = document.getElementById('custom-modal');
            if (existingModal) {
                document.body.removeChild(existingModal);
            }
            
            const modal = document.createElement('div');
            modal.id = 'custom-modal';
            modal.className = 'fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center';
            
            // 创建模态框内容
            const modalContent = document.createElement('div');
            modalContent.className = 'bg-white rounded-lg shadow-lg w-full max-w-md mx-4 p-6 animate-fade-in';
            
            // 创建标题栏
            const modalHeader = document.createElement('div');
            modalHeader.className = 'flex justify-between items-center mb-4';
            
            const titleElement = document.createElement('h3');
            titleElement.className = 'text-xl font-bold';
            titleElement.textContent = title;
            
            const closeButton = document.createElement('button');
            closeButton.id = 'close-custom-modal';
            closeButton.className = 'text-gray-500 hover:text-gray-700';
            closeButton.innerHTML = '<i class="fa fa-times text-xl"></i>';
            
            modalHeader.appendChild(titleElement);
            modalHeader.appendChild(closeButton);
            
            // 将内容添加到模态框
            modalContent.appendChild(modalHeader);
            
            if (typeof content === 'string') {
                const contentDiv = document.createElement('div');
                contentDiv.innerHTML = content;
                modalContent.appendChild(contentDiv);
            } else if (content instanceof Element) {
                modalContent.appendChild(content);
            }
            
            modal.appendChild(modalContent);
            document.body.appendChild(modal);
            
            // 关闭模态框
            closeButton.addEventListener('click', () => {
                document.body.removeChild(modal);
            });
            
            // 点击模态框外部关闭
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    document.body.removeChild(modal);
                }
            });
            
            // 按ESC键关闭
            const handleEsc = (e) => {
                if (e.key === 'Escape') {
                    document.body.removeChild(modal);
                    document.removeEventListener('keydown', handleEsc);
                }
            };
            document.addEventListener('keydown', handleEsc);
        }
        
        // 生成二维码
        function generateQRCode(text, size = 200) {
            const canvas = document.createElement('canvas');
            canvas.width = size;
            canvas.height = size;
            
            // 检查是否有jsQR库可用
            if (typeof jsQR === 'undefined') {
                // 如果没有二维码库，使用文本代替
                const ctx = canvas.getContext('2d');
                ctx.fillStyle = 'white';
                ctx.fillRect(0, 0, size, size);
                ctx.fillStyle = 'black';
                ctx.font = '16px Arial';
                ctx.textAlign = 'center';
                ctx.textBaseline = 'middle';
                
                // 简单地将文本居中显示
                const lines = text.match(/.{1,10}/g) || [text];
                const lineHeight = 20;
                const startY = size / 2 - (lines.length * lineHeight) / 2 + lineHeight / 2;
                
                lines.forEach((line, index) => {
                    ctx.fillText(line, size / 2, startY + index * lineHeight);
                });
            } else {
                // 这里模拟生成二维码（实际应该使用专门的二维码生成库）
                // 由于我们只有jsQR扫描库，这里创建一个简单的图案
                const ctx = canvas.getContext('2d');
                ctx.fillStyle = 'white';
                ctx.fillRect(0, 0, size, size);
                ctx.fillStyle = 'black';
                
                // 创建简单的二维码样式图案
                const moduleSize = Math.floor(size / 20);
                for (let y = 0; y < 20; y++) {
                    for (let x = 0; x < 20; x++) {
                        // 创建伪随机图案，但确保三个角有定位图案
                        if ((x < 4 && y < 4) || 
                            (x > 15 && y < 4) || 
                            (x < 4 && y > 15) ||
                            (x * y * (x - 19) * (y - 19)) % 3 === 0) {
                            ctx.fillRect(x * moduleSize, y * moduleSize, moduleSize, moduleSize);
                        }
                    }
                }
                
                // 不在canvas外部添加文本，确保所有内容都在canvas范围内
                ctx.fillStyle = '#333';
                ctx.font = '12px Arial';
                ctx.textAlign = 'center';
                ctx.fillText(text, size / 2, size - 10); // 在canvas内部底部添加文本
            }
            
            return canvas;
        }
        
        // 初始化同步功能
        function initSyncFeatures() {
            // 检查本地存储中的同步状态
            const syncStatus = localStorage.getItem('syncStatus') || '未同步';
            document.getElementById('sync-status').textContent = syncStatus;
            document.getElementById('sync-status').className = syncStatus === '已同步' ? 'text-success' : 'text-gray-600';
        }
        
        // 保存同步状态
        function saveSyncStatus(status) {
            localStorage.setItem('syncStatus', status);
            document.getElementById('sync-status').textContent = status;
            document.getElementById('sync-status').className = status === '已同步' ? 'text-success' : 'text-gray-600';
        }
        
        // 记录同步历史
        function recordSyncHistory(action, details) {
            let history = JSON.parse(localStorage.getItem('syncHistory') || '[]');
            history.unshift({
                timestamp: new Date().toISOString(),
                action: action,
                details: details
            });
            // 只保留最近10条记录
            if (history.length > 10) {
                history = history.slice(0, 10);
            }
            localStorage.setItem('syncHistory', JSON.stringify(history));
        }

        // 初始化扫码功能 - 优化版本，确保每个扫描器实例完全独立
        function initScanner(videoElementId, onDetected) {
            // 创建唯一标识符，用于区分不同的扫描器实例
            const scannerId = `scanner_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
            let stream = null;
            let scanning = false;
            const video = document.getElementById(videoElementId);
            const canvasElement = document.createElement('canvas');
            const canvas = canvasElement.getContext('2d');
            
            console.log(`初始化扫描器: ${scannerId}, 视频元素: ${videoElementId}`);
            
            // 设置canvas尺寸与视频相同
            function setCanvasDimensions() {
                if (video.videoWidth) {
                    canvasElement.width = video.videoWidth;
                    canvasElement.height = video.videoHeight;
                }
            }
            
            // 实际的二维码和条形码扫描函数
            async function tick() {
                if (!scanning || !stream) {
                    console.log(`扫描器 ${scannerId} 停止扫描: scanning=${scanning}, stream=${!!stream}`);
                    return;
                }
                
                if (video.readyState === video.HAVE_ENOUGH_DATA) {
                    setCanvasDimensions();
                    canvas.drawImage(video, 0, 0, canvasElement.width, canvasElement.height);
                    const imageData = canvas.getImageData(0, 0, canvasElement.width, canvasElement.height);
                    
                    // 检查ZXing库是否存在（适配UMD版本）
                    const zxingInstance = typeof window !== 'undefined' && typeof window.ZXing !== 'undefined' ? window.ZXing : ZXing;
                    if ((typeof ZXing !== 'undefined' && typeof ZXing.BrowserMultiFormatReader !== 'undefined') ||
                        (typeof window !== 'undefined' && typeof window.ZXing !== 'undefined' && typeof window.ZXing.BrowserMultiFormatReader !== 'undefined')) {
                        try {
                            // 为每个扫描器实例创建独立的读取器
                            const readerInstance = typeof window !== 'undefined' && typeof window.ZXing !== 'undefined' && typeof window.ZXing.BrowserMultiFormatReader !== 'undefined' ? window.ZXing.BrowserMultiFormatReader : ZXing.BrowserMultiFormatReader;
                            const barcodeReader = new readerInstance();
                            
                            // 使用ZXing扫描图像数据
                            // 在webview环境中，我们需要使用更兼容的方式
                            let result;
                            if (barcodeReader.decodeFromImageData) {
                                // 优先使用直接的ImageData解码
                                result = await barcodeReader.decodeFromImageData(imageData);
                            } else {
                                // 如果不支持ImageData解码，使用canvas临时创建DataURL进行解码
                                // 创建临时canvas
                                const tempCanvas = document.createElement('canvas');
                                tempCanvas.width = canvasElement.width;
                                tempCanvas.height = canvasElement.height;
                                const tempCtx = tempCanvas.getContext('2d');
                                tempCtx.putImageData(imageData, 0, 0);
                                
                                // 获取DataURL并解码
                                const dataUrl = tempCanvas.toDataURL('image/png');
                                // 使用decodeFromImageUrl进行解码
                                result = await barcodeReader.decodeFromImageUrl(dataUrl);
                            }
                            
                            if (result) {
                                console.log(`扫描器 ${scannerId} 扫描到码: ${result.text}, 格式: ${result.format}`);
                                scanning = false;
                                
                                try {
                                    // 安全地执行回调函数，捕获可能的错误
                                    onDetected(result.text);
                                } catch (callbackError) {
                                    console.error(`扫描器 ${scannerId} 回调执行出错:`, callbackError);
                                    showToast('处理扫描结果时出错', 'error');
                                } finally {
                                    // 确保无论如何都停止扫描器
                                    stopScanner();
                                }
                                return;
                            }
                        } catch (zxingError) {
                            console.warn(`ZXing识别出错（这是正常的，可能是因为画面中没有码）:`, zxingError);
                            // ZXing识别失败是正常的，不需要显示错误提示
                        }
                    } else {
                        console.error('ZXing库未正确加载，无法进行扫描');
                    }
                }
                
                // 继续扫描下一帧
                requestAnimationFrame(tick);
            }
            
            // 创建一个独立的摄像头测试函数，用于诊断问题
            async function testCameraCompatibility() {
                try {
                    const testResults = {
                        browser: navigator.userAgent,
                        secureContext: window.isSecureContext,
                        protocol: window.location.protocol,
                        apis: {
                            mediaDevices: navigator.mediaDevices !== undefined,
                            getUserMedia: navigator.mediaDevices && navigator.mediaDevices.getUserMedia !== undefined,
                            legacyGetUserMedia: navigator.getUserMedia !== undefined,
                            webkitGetUserMedia: navigator.webkitGetUserMedia !== undefined,
                            mozGetUserMedia: navigator.mozGetUserMedia !== undefined,
                            msGetUserMedia: navigator.msGetUserMedia !== undefined
                        }
                    };
                    
                    console.log('摄像头兼容性测试结果:', testResults);
                    return testResults;
                } catch (err) {
                    console.error('兼容性测试失败:', err);
                    return { error: err.message };
                }
            }
            
            // 添加一个全局函数，方便用户手动测试摄像头
            window.testCameraAccess = async function() {
                const results = await testCameraCompatibility();
                let message = '摄像头兼容性测试结果:\n';
                message += '- 浏览器: ' + results.browser.substring(0, 100) + '...\n';
                message += '- 安全上下文: ' + (results.secureContext ? '是' : '否') + '\n';
                message += '- 协议: ' + results.protocol + '\n';
                message += '- 支持的API:\n';
                
                if (results.apis) {
                    for (const [api, supported] of Object.entries(results.apis)) {
                        message += '  - ' + api + ': ' + (supported ? '是' : '否') + '\n';
                    }
                }
                
                showToast(message, 'info');
            };
            
            async function startScanner() {
                try {
                    // 首先运行兼容性测试
                    const compatibility = await testCameraCompatibility();
                    
                    // 增强的摄像头API检测逻辑，支持不同版本的浏览器
                    let getUserMedia = null;
                    let apiName = '';
                    
                    // 检查现代标准API
                    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                        getUserMedia = navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);
                        apiName = 'navigator.mediaDevices.getUserMedia';
                    } 
                    // 检查旧版API（适用于某些旧浏览器）
                    else if (navigator.getUserMedia) {
                        getUserMedia = navigator.getUserMedia.bind(navigator);
                        apiName = 'navigator.getUserMedia';
                    } 
                    // 检查WebKit浏览器旧版API
                    else if (navigator.webkitGetUserMedia) {
                        getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
                        apiName = 'navigator.webkitGetUserMedia';
                    } 
                    // 检查Firefox浏览器旧版API
                    else if (navigator.mozGetUserMedia) {
                        getUserMedia = navigator.mozGetUserMedia.bind(navigator);
                        apiName = 'navigator.mozGetUserMedia';
                    } 
                    // 检查Microsoft浏览器旧版API
                    else if (navigator.msGetUserMedia) {
                        getUserMedia = navigator.msGetUserMedia.bind(navigator);
                        apiName = 'navigator.msGetUserMedia';
                    }
                    
                    // 如果没有任何API可用，显示详细的不支持信息
                    if (!getUserMedia) {
                        let errorMsg = '您的浏览器不支持摄像头访问功能\n';
                        errorMsg += '建议使用Chrome 53+、Firefox 49+、Safari 11+或Edge 16+等现代浏览器\n';
                        errorMsg += '\n兼容性信息:\n';
                        errorMsg += '- 浏览器: ' + compatibility.browser.substring(0, 50) + '...\n';
                        errorMsg += '- 安全上下文: ' + (compatibility.secureContext ? '是' : '否') + '\n';
                        errorMsg += '- 协议: ' + compatibility.protocol + '\n';
                        
                        showToast(errorMsg, 'error');
                        console.error('没有找到支持的getUserMedia API');
                        // 尝试添加一个简单的回退方案
                        tryFallbackCameraAccess();
                        return;
                    }
                    
                    console.log('使用的摄像头API:', apiName);
                    
                    // 增强的安全上下文检测
                    if (!window.isSecureContext) {
                        console.log('非安全上下文访问摄像头');
                    }
                    
                    try {
                        // 优化权限请求配置
                        const cameraConfig = {
                            video: {
                                facingMode: 'environment', // 优先使用后置摄像头
                                width: { ideal: 1280 },
                                height: { ideal: 720 }
                            }
                        };
                        
                        // 直接尝试调用getUserMedia来触发权限请求弹窗
                        // 使用try-catch来确保即使配置不兼容也能降级
                        try {
                            // 根据检测到的API类型使用适当的方式调用
                            if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                                // 现代标准API使用Promise
                                stream = await navigator.mediaDevices.getUserMedia(cameraConfig);
                            } else if (getUserMedia) {
                                // 旧版API使用回调方式
                                stream = await new Promise((resolve, reject) => {
                                    getUserMedia(cameraConfig, resolve, reject);
                                });
                            }
                        } catch (configError) {
                            console.warn('高级配置失败，使用最简配置:', configError);
                            // 降级到最简配置，提高兼容性
                            if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                                stream = await navigator.mediaDevices.getUserMedia({ video: true });
                            } else if (getUserMedia) {
                                stream = await new Promise((resolve, reject) => {
                                    getUserMedia({ video: true }, resolve, reject);
                                });
                            }
                        }
                        
                        // 处理不同浏览器的视频源设置方式
                        if ('srcObject' in video) {
                            video.srcObject = stream;
                        } else {
                            // 旧版浏览器可能需要使用createObjectURL
                            video.src = window.URL.createObjectURL(stream);
                        }
                        
                        scanning = true;
                        
                        // 等待视频元数据加载完成
                        video.onloadedmetadata = () => {
                            try {
                                // 处理不同浏览器的视频播放方式
                                if (video.play) {
                                    const playPromise = video.play();
                                    
                                    // 检查play()是否返回Promise
                                    if (playPromise !== undefined) {
                                        playPromise.then(() => {
                                            console.log('摄像头启动成功，开始扫描');
                                            // 开始扫描
                                            tick();
                                        }).catch(playErr => {
                                            console.error('无法播放视频流:', playErr);
                                            showToast('无法启动摄像头预览，请检查设备状态', 'error');
                                            stopScanner();
                                        });
                                    } else {
                                        // 旧版浏览器可能不返回Promise
                                        console.log('摄像头启动成功，开始扫描');
                                        tick();
                                    }
                                } else {
                                    console.error('视频元素不支持play方法');
                                    showToast('无法播放摄像头预览，请使用现代浏览器', 'error');
                                    stopScanner();
                                }
                            } catch (playErr) {
                                console.error('播放视频流时出错:', playErr);
                                showToast('无法启动摄像头预览，请检查设备状态', 'error');
                                stopScanner();
                            }
                        };
                    } catch (err) {
                        console.error('获取摄像头流时出错:', err);
                        // 提供更具体的错误信息
                        let errorMsg = '无法访问摄像头';
                        
                        if (err.name === 'NotAllowedError') {
                            errorMsg += ': 摄像头权限被拒绝\n请在浏览器设置中启用摄像头权限';
                        } else if (err.name === 'NotFoundError') {
                            errorMsg += ': 未找到可用的摄像头设备';
                        } else if (err.name === 'NotReadableError') {
                            errorMsg += ': 摄像头被其他应用占用\n请关闭其他使用摄像头的应用';
                        } else if (err.name === 'SecurityError') {
                            errorMsg += ': 安全错误\n浏览器阻止了摄像头访问';
                        } else if (err.name === 'OverconstrainedError') {
                            errorMsg += ': 摄像头配置不兼容';
                        } else {
                            errorMsg += ': ' + err.message || '未知错误';
                        }
                        
                        showToast(errorMsg, 'error');
                        // 尝试回退方案
                        tryFallbackCameraAccess();
                    }
                    
                } catch (err) {
                    console.error('无法访问摄像头:', err);
                    console.error('错误详情:', JSON.stringify(err, null, 2));
                    
                    // 提供更具体的错误信息
                    if (err.name === 'NotAllowedError') {
                        showToast('摄像头权限被拒绝，请在浏览器设置中启用摄像头权限\n提示：请检查浏览器权限设置和设备隐私设置', 'error');
                    } else if (err.name === 'NotFoundError') {
                        showToast('未找到可用的摄像头设备', 'error');
                    } else if (err.name === 'NotReadableError') {
                        showToast('摄像头被其他应用占用，请关闭其他使用摄像头的应用', 'error');
                    } else if (err.name === 'SecurityError') {
                        showToast('安全错误：浏览器阻止了摄像头访问\n请检查浏览器隐私设置和安全策略', 'error');
                    } else if (err.name === 'OverconstrainedError') {
                        showToast('摄像头配置不兼容，请尝试使用其他设备', 'error');
                    } else {
                        showToast('无法访问摄像头，请检查权限设置和设备状态\n错误: ' + err.name, 'error');
                    }
                }
            }
            
            // 停止扫描器 - 确保完全停止所有流和活动
            function stopScanner() {
                console.log(`扫描器 ${scannerId} 正在停止`);
                if (stream) {
                    // 停止所有视频轨道
                    stream.getTracks().forEach(track => {
                        try {
                            track.stop();
                        } catch (e) {
                            console.warn(`扫描器 ${scannerId} 停止轨道时出错:`, e);
                        }
                    });
                    video.srcObject = null;
                    stream = null;
                }
                // 确保扫描状态被重置
                scanning = false;
                console.log(`扫描器 ${scannerId} 已完全停止`);
            }
            
            return { startScanner, stopScanner };
        }

        // 生成付款二维码
        function generatePaymentQR(amount) {
            if (!window.paymentManager) {
                console.error('paymentManager未初始化');
                return;
            }
            
            // 获取当前选择的支付平台
            const selectedPlatform = document.getElementById('payment-platform-selector')?.value || 'wechat';
            
            // 更新显示的金额
            document.getElementById('payment-amount').textContent = `¥${amount}`;
            
            // 获取支付配置
            const paymentConfig = window.paymentManager.getPaymentConfig();
            
            // 生成带金额的收款码
            const qrCodeUrl = window.paymentManager.generatePaymentQRCode(selectedPlatform, parseFloat(amount));
            
            // 获取图片元素并设置src
            const qrImage = document.getElementById('dynamic-payment-qr');
            if (qrImage && qrCodeUrl) {
                qrImage.src = qrCodeUrl;
                qrImage.style.display = 'block';
            }
            
            // 显示对应的平台图标和名称
            if (document.getElementById('select-wechat') && document.getElementById('select-alipay')) {
                document.getElementById('select-wechat').classList.toggle('bg-green-100', selectedPlatform === 'wechat');
                document.getElementById('select-wechat').classList.toggle('text-green-600', selectedPlatform === 'wechat');
                document.getElementById('select-alipay').classList.toggle('bg-blue-100', selectedPlatform === 'alipay');
                document.getElementById('select-alipay').classList.toggle('text-blue-600', selectedPlatform === 'alipay');
            }
            
            // 显示提示信息
            const platformName = selectedPlatform === 'wechat' ? '微信' : '支付宝';
            showToast(`${platformName}收款码已生成，请让顾客扫描`, 'success');
        }

        // 全局变量用于分页状态
        let currentProductPage = 1;
        const PRODUCTS_PER_PAGE = 10;
        
        // 渲染商品列表
        function renderProductList() {
            if (!window.dataStore) {
                console.error('dataStore未初始化');
                return;
            }
            const productList = document.getElementById('product-list');
            const searchTerm = document.getElementById('product-search').value.toLowerCase();
            const selectedCategory = document.getElementById('product-category-filter')?.value || '';
            
            // 获取分页数据，支持按分类和关键词搜索
            const productResult = window.dataStore.getProductsByPage(currentProductPage, PRODUCTS_PER_PAGE, searchTerm, selectedCategory);
            const { items: products, total, totalPages } = productResult;
            
            // 渲染商品列表
            if (products.length === 0) {
                productList.innerHTML = '<tr><td colspan="7" class="px-3 py-8 text-center text-gray-500">暂无商品数据</td></tr>';
                document.getElementById('pagination-controls')?.remove();
                return;
            }
            
            // 为移动端和桌面端使用不同的显示方式，移除分类列
            productList.innerHTML = products.map(product => `
                <tr>
                    <td class="px-3 py-4">${product.name}</td>
                    <td class="px-3 py-4 whitespace-nowrap">¥${product.price}</td>
                    <td class="px-3 py-4 whitespace-nowrap">
                        <span class="${product.stock <= 5 ? 'text-danger font-medium' : ''}">${product.stock || 0}</span>
                    </td>
                    <td class="px-3 py-4 whitespace-nowrap">
                        <button class="text-primary mr-3" onclick="editProduct('${product.barcode}')">
                            <i class="fa fa-edit"></i>
                        </button>
                        <button class="text-danger" onclick="deleteProduct('${product.barcode}')">
                            <i class="fa fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `).join('');
            
            // 添加或更新分页控件
            let paginationContainer = document.getElementById('pagination-controls');
            if (!paginationContainer) {
                // 创建分页容器
                const productTableContainer = productList.parentElement.parentElement;
                paginationContainer = document.createElement('div');
                paginationContainer.id = 'pagination-controls';
                paginationContainer.className = 'mt-4 flex justify-center items-center space-x-2';
                productTableContainer.parentNode.appendChild(paginationContainer);
            }
            
            // 渲染分页控件
            paginationContainer.innerHTML = `
                <button id="prev-page" class="btn-secondary px-3 py-1 rounded ${currentProductPage === 1 ? 'opacity-50 cursor-not-allowed' : ''}">
                    <i class="fa fa-chevron-left"></i>
                </button>
                <span class="text-sm text-gray-600">第 ${currentProductPage} / ${totalPages} 页</span>
                <span class="text-sm text-gray-600">共 ${total} 条数据</span>
                <button id="next-page" class="btn-secondary px-3 py-1 rounded ${currentProductPage === totalPages ? 'opacity-50 cursor-not-allowed' : ''}">
                    <i class="fa fa-chevron-right"></i>
                </button>
            `;
            
            // 绑定分页事件
            document.getElementById('prev-page').addEventListener('click', function() {
                if (currentProductPage > 1) {
                    currentProductPage--;
                    renderProductList();
                }
            });
            
            document.getElementById('next-page').addEventListener('click', function() {
                if (currentProductPage < totalPages) {
                    currentProductPage++;
                    renderProductList();
                }
            });
        }

        // 编辑商品
        function editProduct(barcode) {
            if (!window.dataStore) {
                console.error('dataStore未初始化');
                return;
            }
            const product = window.dataStore.findProduct(barcode);
            if (product) {
                document.getElementById('product-barcode').value = barcode;
                document.getElementById('product-name').value = product.name;
                document.getElementById('product-category').value = product.category ? (product.category || '') : '';
                document.getElementById('product-cost').value = product.cost ? (product.cost || '') : '';
                document.getElementById('product-price').value = product.price;
                document.getElementById('product-stock').value = product.stock || 0;
                document.getElementById('product-form').classList.remove('hidden');
                navigateTo('scan-product');
            }
        }

        // 删除商品
        function deleteProduct(barcode) {
            if (!window.dataStore) {
                console.error('dataStore未初始化');
                return;
            }
            if (confirm('确定要删除这个商品吗？')) {
                window.dataStore.deleteProduct(barcode);
                renderProductList();
                showToast('商品已删除', 'success');
                updateHomeOverview();
            }
        }

        // 渲染购物车
        function renderCart() {
            const cartItems = document.getElementById('cart-items');
            const totalItemsEl = document.getElementById('total-items');
            const totalAmountEl = document.getElementById('total-amount');
            
            if (!window.dataStore) {
                console.error('dataStore未初始化');
                cartItems.innerHTML = '<div class="text-center text-gray-500 py-6">购物车为空</div>';
                totalItemsEl.textContent = '0';
                totalAmountEl.textContent = '¥0.00';
                return;
            }
            
            if (window.dataStore.currentCart.length === 0) {
                cartItems.innerHTML = '<div class="text-center text-gray-500 py-6">购物车为空</div>';
                totalItemsEl.textContent = '0';
                totalAmountEl.textContent = '¥0.00';
                return;
            }
            
            // 计算总计
            const totalItems = window.dataStore.currentCart.reduce((sum, item) => sum + item.quantity, 0);
            const totalAmount = window.dataStore.currentCart.reduce((sum, item) => {
                return sum + (parseFloat(item.price) * item.quantity);
            }, 0);
            
            // 更新购物车列表
            cartItems.innerHTML = window.dataStore.currentCart.map(item => `
                <div class="flex items-center justify-between p-2 border-b">
                    <div>
                        <div class="font-medium">${item.name}</div>
                        <div class="text-sm text-gray-500">${item.barcode}</div>
                    </div>
                    <div class="flex items-center">
                        <button class="w-6 h-6 flex items-center justify-center text-gray-500" onclick="updateCartItem('${item.barcode}', ${item.quantity - 1})">-</button>
                        <span class="w-8 text-center">${item.quantity}</span>
                        <button class="w-6 h-6 flex items-center justify-center text-gray-500" onclick="updateCartItem('${item.barcode}', ${item.quantity + 1})">+</button>
                        <span class="ml-4 font-medium">¥${(parseFloat(item.price) * item.quantity).toFixed(2)}</span>
                        <button class="ml-2 text-danger" onclick="removeFromCart('${item.barcode}')">
                            <i class="fa fa-times"></i>
                        </button>
                    </div>
                </div>
            `).join('');
            
            // 更新总计
            totalItemsEl.textContent = totalItems;
            totalAmountEl.textContent = `¥${totalAmount.toFixed(2)}`;
        }

        // 更新购物车商品数量
        function updateCartItem(barcode, quantity) {
            if (!window.dataStore) {
                console.error('dataStore未初始化');
                return;
            }
            window.dataStore.updateCartItemQuantity(barcode, quantity);
            renderCart();
        }

        // 从购物车移除商品
        function removeFromCart(barcode) {
            if (!window.dataStore) {
                console.error('dataStore未初始化');
                return;
            }
            window.dataStore.removeFromCart(barcode);
            renderCart();
        }

        // 全局变量用于订单分页和筛选
        let currentOrderPage = 1;
        const ORDERS_PER_PAGE = 10;
        let currentOrderStatus = 'all'; // 默认为全部订单
        
        // 在页面加载时添加订单状态筛选控件
        function addOrderStatusFilter() {
            // 查找订单标题旁边的容器来添加筛选控件
            const ordersHeader = document.querySelector('#recent-orders-section h2');
            if (ordersHeader && !document.getElementById('order-status-filter')) {
                // 创建筛选控件
                const filterContainer = document.createElement('div');
                filterContainer.id = 'order-status-filter';
                filterContainer.className = 'flex items-center ml-4';
                filterContainer.innerHTML = `
                    <label for="status-select" class="text-sm text-gray-600 mr-2">状态:</label>
                    <select id="status-select" class="text-sm border border-gray-300 rounded px-2 py-1 focus:outline-none focus:ring-1 focus:ring-primary focus:border-primary">
                        <option value="all">全部</option>
                        <option value="pending">待支付</option>
                        <option value="paid">已支付</option>
                        <option value="cancelled">已取消</option>
                    </select>
                `;
                
                // 添加到标题旁边
                ordersHeader.parentNode.insertBefore(filterContainer, ordersHeader.nextSibling);
                
                // 添加筛选事件监听
                document.getElementById('status-select').addEventListener('change', function() {
                    currentOrderPage = 1; // 重置为第一页
                    currentOrderStatus = this.value;
                    renderRecentOrders();
                });
            }
        }
        
        // 渲染最近订单
        function renderRecentOrders() {
            if (!window.dataStore) {
                console.error('dataStore未初始化');
                return;
            }
            const recentOrdersTableEl = document.getElementById('recent-orders-table');
            const recentOrdersCardsEl = document.getElementById('recent-orders-cards');
            
            // 确保筛选控件存在
            addOrderStatusFilter();
            
            // 获取分页订单数据，支持状态筛选
            const orderResult = window.dataStore.getOrdersByPage(currentOrderPage, ORDERS_PER_PAGE, currentOrderStatus);
            const { items: orders, total, totalPages } = orderResult;
            
            if (orders.length === 0) {
                recentOrdersTableEl.innerHTML = '<tr><td colspan="5" class="px-3 py-8 text-center text-gray-500">暂无订单数据</td></tr>';
                recentOrdersCardsEl.innerHTML = '<div class="text-center py-8 text-gray-500">暂无订单数据</div>';
                document.getElementById('order-pagination-controls')?.remove();
                return;
            }
            
            // 获取订单状态显示文本和样式
            function getOrderStatusDisplay(order) {
                switch (order.status) {
                    case 'pending':
                        return {
                            text: '待支付',
                            className: 'px-2 py-1 bg-yellow-100 text-yellow-800 rounded-full text-xs'
                        };
                    case 'paid':
                        return {
                            text: '已支付',
                            className: 'px-2 py-1 bg-green-100 text-green-800 rounded-full text-xs'
                        };
                    case 'cancelled':
                        return {
                            text: '已取消',
                            className: 'px-2 py-1 bg-red-100 text-red-800 rounded-full text-xs'
                        };
                    default:
                        return {
                            text: '未知状态',
                            className: 'px-2 py-1 bg-gray-100 text-gray-800 rounded-full text-xs'
                        };
                }
            }
            
            // 渲染表格布局 (大屏幕)
            recentOrdersTableEl.innerHTML = orders.map(order => {
                const itemCount = order.items.reduce((sum, item) => sum + item.quantity, 0);
                const status = getOrderStatusDisplay(order);
                return `
                    <tr class="hover:bg-gray-50 transition-colors cursor-pointer" data-order-id="${order.id}">
                        <td class="px-3 py-4 whitespace-nowrap">${order.id}</td>
                        <td class="px-3 py-4 whitespace-nowrap">${new Date(order.date).toLocaleString()}</td>
                        <td class="px-3 py-4 whitespace-nowrap">${itemCount}</td>
                        <td class="px-3 py-4 whitespace-nowrap font-medium">¥${order.totalAmount}</td>
                        <td class="px-3 py-4 whitespace-nowrap">
                            <span class="${status.className}">${status.text}</span>
                        </td>
                    </tr>
                `;
            }).join('');
                
            // 渲染卡片布局 (移动端)
            recentOrdersCardsEl.innerHTML = orders.map(order => {
                const itemCount = order.items.reduce((sum, item) => sum + item.quantity, 0);
                const orderDate = new Date(order.date);
                const formattedDate = `${orderDate.getMonth() + 1}/${orderDate.getDate()} ${orderDate.getHours().toString().padStart(2, '0')}:${orderDate.getMinutes().toString().padStart(2, '0')}`;
                const status = getOrderStatusDisplay(order);
                    
                return `
                    <div class="bg-white rounded-lg shadow-sm p-4 mb-3 border border-gray-100 cursor-pointer" data-order-id="${order.id}">
                        <div class="flex justify-between items-center mb-2">
                            <span class="text-sm font-medium text-gray-700">${order.id}</span>
                            <span class="text-sm text-gray-500">${formattedDate}</span>
                        </div>
                        <div class="flex justify-between items-center text-gray-600 mb-2">
                            <span class="text-sm">${itemCount} 件商品</span>
                            <span class="text-lg font-bold text-primary">¥${order.totalAmount}</span>
                        </div>
                        <div class="flex justify-end">
                            <span class="${status.className}">${status.text}</span>
                        </div>
                    </div>
                `;
            }).join('');
            
            // 添加或更新分页控件
            let paginationContainer = document.getElementById('order-pagination-controls');
            // 将分页控件移到订单详情部分的末尾
            const ordersContainer = document.getElementById('recent-orders-cards').parentElement;
            if (!paginationContainer && ordersContainer) {
                // 创建分页容器
                paginationContainer = document.createElement('div');
                paginationContainer.id = 'order-pagination-controls';
                paginationContainer.className = 'mt-4 flex justify-center items-center space-x-2';
                ordersContainer.appendChild(paginationContainer);
            }
            
            // 渲染分页控件
            if (paginationContainer) {
                paginationContainer.innerHTML = `
                    <button id="prev-order-page" class="btn-secondary px-3 py-1 rounded ${currentOrderPage === 1 ? 'opacity-50 cursor-not-allowed' : ''}">
                        <i class="fa fa-chevron-left"></i>
                    </button>
                    <span class="text-sm text-gray-600">第 ${currentOrderPage} / ${totalPages} 页</span>
                    <span class="text-sm text-gray-600">共 ${total} 条数据</span>
                    <button id="next-order-page" class="btn-secondary px-3 py-1 rounded ${currentOrderPage === totalPages ? 'opacity-50 cursor-not-allowed' : ''}">
                        <i class="fa fa-chevron-right"></i>
                    </button>
                `;
                
                // 绑定分页事件
                document.getElementById('prev-order-page').addEventListener('click', function() {
                    if (currentOrderPage > 1) {
                        currentOrderPage--;
                        renderRecentOrders();
                    }
                });
                
                document.getElementById('next-order-page').addEventListener('click', function() {
                    if (currentOrderPage < totalPages) {
                        currentOrderPage++;
                        renderRecentOrders();
                    }
                });
            }
            
            // 绑定订单点击事件
            document.querySelectorAll('#recent-orders-table tr[data-order-id]').forEach(row => {
                row.addEventListener('click', function() {
                    const orderId = this.getAttribute('data-order-id');
                    showOrderDetail(orderId);
                });
            });
            
            document.querySelectorAll('#recent-orders-cards [data-order-id]').forEach(card => {
                card.addEventListener('click', function() {
                    const orderId = this.getAttribute('data-order-id');
                    showOrderDetail(orderId);
                });
            });
        }
        
        // 显示订单详情
        function showOrderDetail(orderId) {
            if (!window.dataStore) {
                console.error('dataStore未初始化');
                return;
            }
            
            const order = window.dataStore.getOrderById(orderId);
            if (!order) {
                showToast('未找到订单', 'error');
                return;
            }
            
            // 填充订单详情
            document.getElementById('modal-order-id').textContent = `订单详情 - ${order.id}`;
            document.getElementById('modal-order-date').textContent = new Date(order.date).toLocaleString();
            
            // 计算商品总数
            const totalItems = order.items.reduce((sum, item) => sum + item.quantity, 0);
            document.getElementById('modal-total-items').textContent = totalItems;
            document.getElementById('modal-total-amount').textContent = `¥${order.totalAmount}`;
            
            // 根据订单状态动态更新状态显示
            const statusEl = document.getElementById('modal-order-status');
            const statusContainer = document.getElementById('confirm-payment-container');
            
            switch (order.status) {
                case 'pending':
                    statusEl.textContent = '待支付';
                    statusEl.className = 'font-medium text-yellow-600';
                    statusContainer.classList.remove('hidden'); // 显示确认收款按钮
                    break;
                case 'paid':
                    statusEl.textContent = '已支付';
                    statusEl.className = 'font-medium text-green-600';
                    statusContainer.classList.add('hidden'); // 隐藏确认收款按钮
                    break;
                case 'cancelled':
                    statusEl.textContent = '已取消';
                    statusEl.className = 'font-medium text-red-600';
                    statusContainer.classList.add('hidden'); // 隐藏确认收款按钮
                    break;
                default:
                    statusEl.textContent = '未知状态';
                    statusEl.className = 'font-medium text-gray-600';
                    statusContainer.classList.add('hidden'); // 隐藏确认收款按钮
            }
            
            // 绑定确认收款按钮事件（每次打开模态框时重新绑定，避免事件重复绑定）
            const confirmBtn = document.getElementById('confirm-payment-btn');
            
            // 先移除之前可能存在的事件监听器
            const newConfirmBtn = confirmBtn.cloneNode(true);
            confirmBtn.parentNode.replaceChild(newConfirmBtn, confirmBtn);
            
            // 重新绑定事件监听器
            newConfirmBtn.addEventListener('click', function() {
                confirmOrderPayment(order.id, order.totalAmount);
            });
            
            // 渲染订单商品列表
            const orderItemsEl = document.getElementById('modal-order-items');
            orderItemsEl.innerHTML = order.items.map(item => `
                <div class="flex justify-between items-center p-2 border-b">
                    <div class="flex-1">
                        <div class="font-medium">${item.name}</div>
                        <div class="text-sm text-gray-500">${item.barcode}</div>
                    </div>
                    <div class="flex items-center space-x-4">
                        <span class="text-sm">x${item.quantity}</span>
                        <span class="font-medium">¥${item.price}</span>
                        <span class="font-medium">¥${(parseFloat(item.price) * item.quantity).toFixed(2)}</span>
                    </div>
                </div>
            `).join('');
            
            // 显示模态框
            const modal = document.getElementById('order-detail-modal');
            modal.classList.remove('hidden');
            
            // 防止页面滚动
            document.body.style.overflow = 'hidden';
        }
        
        // 确认订单支付
        function confirmOrderPayment(orderId, amount) {
            if (!window.dataStore) {
                console.error('dataStore未初始化');
                return;
            }
            
            // 显示确认对话框
            if (confirm(`确认收到该订单的款项 (¥${amount}) 吗？确认后订单状态将更新为已支付。`)) {
                try {
                    // 更新订单状态为已支付
                    const success = window.dataStore.updateOrderStatus(orderId, 'paid', 'manual');
                    
                    if (success) {
                        showToast('订单已确认收款', 'success');
                        
                        // 在Android WebView环境中，可以通知原生端订单已完成
                        if (typeof window.Android !== 'undefined' && typeof window.Android.notifyOrderCompleted === 'function') {
                            try {
                                window.Android.notifyOrderCompleted(orderId);
                            } catch (androidError) {
                                console.error('调用Android原生接口通知订单完成失败:', androidError);
                            }
                        }
                        
                        // 刷新订单列表和详情
                        renderRecentOrders();
                        showOrderDetail(orderId);
                    } else {
                        showToast('确认收款失败，请重试', 'error');
                    }
                } catch (error) {
                    console.error('确认收款时出错:', error);
                    showToast('确认收款失败，请重试', 'error');
                }
            }
        }
        
        // 关闭订单详情模态框
        function closeOrderDetailModal() {
            const modal = document.getElementById('order-detail-modal');
            modal.classList.add('hidden');
            
            // 恢复页面滚动
            document.body.style.overflow = '';
        }

        // 更新首页概览数据
        function updateHomeOverview() {
            if (!window.dataStore) {
                console.error('dataStore未初始化');
                return;
            }
            document.getElementById('today-sales').textContent = `¥${window.dataStore.getTodaySalesAmount()}`;
            document.getElementById('today-orders').textContent = window.dataStore.getTodayOrderCount();
            document.getElementById('total-products').textContent = window.dataStore.getAllProducts().length;
            document.getElementById('stock-alerts').textContent = window.dataStore.getLowStockProducts().length;
        }

        // 更新统计图表
        function updateCharts() {
            // 销售额趋势图
            const salesCtx = document.getElementById('sales-chart').getContext('2d');
            
            // 准备过去7天的数据
            const days = [];
            const salesData = [];
            
            for (let i = 6; i >= 0; i--) {
                const date = new Date();
                date.setDate(date.getDate() - i);
                const dateStr = date.toISOString().split('T')[0];
                days.push(date.getMonth() + 1 + '/' + date.getDate());
                
                // 计算当天销售额
            const daySales = window.dataStore.orders
                .filter(order => order.date.startsWith(dateStr))
                .reduce((sum, order) => sum + parseFloat(order.totalAmount), 0);
            salesData.push(daySales);
            }
            
            // 销毁已存在的图表
            if (window.salesChartInstance) {
                window.salesChartInstance.destroy();
            }
            
            window.salesChartInstance = new Chart(salesCtx, {
                type: 'line',
                data: {
                    labels: days,
                    datasets: [{
                        label: '销售额 (¥)',
                        data: salesData,
                        backgroundColor: 'rgba(37, 99, 235, 0.2)',
                        borderColor: 'rgba(37, 99, 235, 1)',
                        borderWidth: 2,
                        tension: 0.3,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
            
            // 商品销售排行图
            const productsCtx = document.getElementById('products-chart').getContext('2d');
            
            // 计算每个商品的总销售量
            const productSales = {};
            
            window.dataStore.orders.forEach(order => {
                order.items.forEach(item => {
                    if (!productSales[item.barcode]) {
                        productSales[item.barcode] = {
                            name: item.name,
                            total: 0
                        };
                    }
                    productSales[item.barcode].total += item.quantity;
                });
            });
            
            // 获取销量前5的商品
            const topProducts = Object.values(productSales)
                .sort((a, b) => b.total - a.total)
                .slice(0, 5);
            
            // 销毁已存在的图表
            if (window.productsChartInstance) {
                window.productsChartInstance.destroy();
            }
            
            window.productsChartInstance = new Chart(productsCtx, {
                type: 'bar',
                data: {
                    labels: topProducts.map(p => p.name),
                    datasets: [{
                        label: '销售量',
                        data: topProducts.map(p => p.total),
                        backgroundColor: 'rgba(16, 185, 129, 0.7)',
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                precision: 0
                            }
                        }
                    }
                }
            });
            
            // 更新最近订单列表
            renderRecentOrders();
        }

        // 添加新产品函数
        function addNewProduct() {
            // 清空表单，准备添加新产品
            document.getElementById('product-barcode').value = '';
            document.getElementById('product-name').value = '';
            document.getElementById('product-category').value = '';
            document.getElementById('product-cost').value = '';
            document.getElementById('product-price').value = '';
            document.getElementById('product-stock').value = '0';
            document.getElementById('product-form').classList.remove('hidden');
            navigateTo('scan-product');
        }

        // 初始化应用
        function initApp() {
            // 使用全局dataStore变量
            
            // 检查是否有未完成的支付订单
            checkPendingOrders();
            
            // 初始化页面导航
            document.querySelectorAll('.menu-item').forEach(btn => {
                btn.addEventListener('click', () => {
                    navigateTo(btn.dataset.target);
                });
            });
            
            document.querySelectorAll('.footer-item').forEach(btn => {
                btn.addEventListener('click', () => {
                    navigateTo(btn.dataset.target);
                });
            });
            
            // 侧边菜单控制
            document.getElementById('menu-btn').addEventListener('click', () => {
                document.getElementById('sidebar').classList.remove('translate-x-full');
            });
            
            document.getElementById('close-menu').addEventListener('click', () => {
                document.getElementById('sidebar').classList.add('translate-x-full');
            });
            
            // 初始化商品扫描器 - 仅用于商品添加页面
            const productScanner = initScanner('scan-preview', (barcode) => {
                console.log('商品扫描器回调执行 - 仅用于填充表单，不执行页面跳转');
                if (!window.dataStore) {
                    console.error('dataStore未初始化');
                    return;
                }
                // 清理条形码数据
                const cleanBarcode = typeof barcode === 'string' ? barcode.trim() : String(barcode).trim();
                const existingProduct = window.dataStore.findProduct(cleanBarcode);
                
                document.getElementById('product-barcode').value = cleanBarcode;
                document.getElementById('product-name').value = existingProduct ? existingProduct.name : '';
                document.getElementById('product-category').value = existingProduct ? (existingProduct.category || '') : '';
                document.getElementById('product-cost').value = existingProduct ? (existingProduct.cost || '') : '';
                document.getElementById('product-price').value = existingProduct ? existingProduct.price : '';
                document.getElementById('product-stock').value = existingProduct ? (existingProduct.stock || 0) : 0;
                
                // 只显示表单元素，不进行页面跳转
                document.getElementById('product-form').classList.remove('hidden');
                showToast(`已扫描条形码: ${cleanBarcode}`, 'info');
            });
            
            // 开始扫描按钮 - 修改为与编辑按钮打开相同页面体验
            document.getElementById('start-scan').addEventListener('click', () => {
                // 清空表单，准备扫描新产品
                document.getElementById('product-barcode').value = '';
                document.getElementById('product-name').value = '';
                document.getElementById('product-category').value = '';
                document.getElementById('product-cost').value = '';
                document.getElementById('product-price').value = '';
                document.getElementById('product-stock').value = '0';
                document.getElementById('product-form').classList.remove('hidden');
                productScanner.startScanner();
            });
            
            // 保存商品按钮
            document.getElementById('save-product').addEventListener('click', () => {
                if (!window.dataStore) {
                    console.error('dataStore未初始化');
                    showToast('数据存储初始化失败', 'error');
                    return;
                }
                // 获取并清理条形码数据
                const barcodeInput = document.getElementById('product-barcode').value;
                const barcode = typeof barcodeInput === 'string' ? barcodeInput.trim() : String(barcodeInput).trim();
                const name = document.getElementById('product-name').value;
                const category = document.getElementById('product-category').value;
                const cost = document.getElementById('product-cost').value;
                const price = document.getElementById('product-price').value;
                const stock = document.getElementById('product-stock').value;
                
                if (!barcode || !name || !price) {
                    showToast('请填写完整的商品信息', 'warning');
                    return;
                }
                
                const product = {
                    barcode,
                    name,
                    category,
                    cost: cost || '0.00',
                    price,
                    stock: parseInt(stock) || 0
                };
                
                try {
                    const saveResult = window.dataStore.saveProduct(product);
                    if (saveResult) {
                        showToast('商品已保存', 'success');
                        navigateTo('product-management');
                    } else {
                        showToast('商品保存失败，请稍后重试', 'error');
                    }
                } catch (error) {
                    console.error('保存商品时发生错误:', error);
                    showToast('保存失败: ' + error.message, 'error');
                }
            });
            
            // 取消商品编辑
            document.getElementById('cancel-product').addEventListener('click', () => {
                document.getElementById('product-form').classList.add('hidden');
            });
            
            // 商品搜索
            document.getElementById('product-search').addEventListener('input', function() {
                // 搜索时重置到第一页
                currentProductPage = 1;
                renderProductList();
            });
            
            // 商品分类筛选
            if (document.getElementById('product-category-filter')) {
                document.getElementById('product-category-filter').addEventListener('change', function() {
                    // 筛选时重置到第一页
                    currentProductPage = 1;
                    renderProductList();
                });
            }
            
            // 订单详情模态框关闭按钮
            document.getElementById('close-modal').addEventListener('click', closeOrderDetailModal);
            
            // 点击模态框外部关闭
            document.getElementById('order-detail-modal').addEventListener('click', function(e) {
                if (e.target === this) {
                    closeOrderDetailModal();
                }
            });
            
            // ESC键关闭模态框
            document.addEventListener('keydown', function(e) {
                if (e.key === 'Escape' && !document.getElementById('order-detail-modal').classList.contains('hidden')) {
                    closeOrderDetailModal();
                }
            });
            
            // 初始化收银台扫描器
            const checkoutScanner = initScanner('checkout-preview', (barcode) => {
                if (!window.dataStore) {
                    console.error('dataStore未初始化');
                    return;
                }
                
                try {
                    const product = window.dataStore.addToCart(barcode);
                    
                    if (product) {
                        showToast(`已添加: ${product.name}`, 'success');
                        renderCart();
                        // 添加TTS语音播报
                        if (window.ttsManager) {
                            window.ttsManager.speakProductScanned(product);
                        }
                    } else {
                        showToast(`未找到商品: ${barcode}`, 'error');
                        // 添加TTS语音播报
                        if (window.ttsManager) {
                            window.ttsManager.speak('未找到商品');
                        }
                    }
                } catch (error) {
                    // 处理库存不足错误
                    if (error.message.includes('库存不足')) {
                        showToast(error.message, 'error');
                        // 添加TTS语音播报
                        if (window.ttsManager) {
                            window.ttsManager.speak('商品库存不足');
                        }
                    } else {
                        // 处理其他错误
                        console.error('添加商品失败:', error);
                        showToast('添加商品失败', 'error');
                    }
                }
                
                // 确保在收银台扫描后不会跳转到商品添加页面
                // 阻止任何可能的默认行为或事件冒泡
                event?.preventDefault?.();
                event?.stopPropagation?.();
            });
            
            // 开始收银扫描
            document.getElementById('start-checkout-scan').addEventListener('click', () => {
                checkoutScanner.startScanner();
            });
            
            // 清空购物车
            document.getElementById('clear-cart').addEventListener('click', () => {
                if (!window.dataStore) {
                    console.error('dataStore未初始化');
                    return;
                }
                if (window.dataStore.currentCart.length > 0 && confirm('确定要清空购物车吗？')) {
                    window.dataStore.clearCart();
                    renderCart();
                    showToast('购物车已清空', 'success');
                    // 添加TTS语音播报
                    if (window.ttsManager) {
                        window.ttsManager.speak('购物车已清空');
                    }
                }
            });
            
            // 处理付款
            document.getElementById('process-payment').addEventListener('click', () => {
                if (!window.dataStore) {
                    console.error('dataStore未初始化');
                    return;
                }
                if (window.dataStore.currentCart.length === 0) {
                    showToast('购物车为空，无法结算', 'warning');
                    return;
                }
                
                // 计算购物车总金额
                const totalAmount = window.dataStore.currentCart.reduce((sum, item) => {
                    return sum + (parseFloat(item.price) * item.quantity);
                }, 0).toFixed(2);
                document.getElementById('transaction-amount').value = totalAmount;
                
                // 直接显示收款码界面
                generatePaymentQR(totalAmount);
                document.getElementById('qr-payment').classList.remove('hidden');
            });
            
            // 显示收款码
            document.getElementById('show-qr').addEventListener('click', () => {
                if (!window.dataStore) {
                    console.error('dataStore未初始化');
                    return;
                }
                const totalAmount = window.dataStore.currentCart.reduce((sum, item) => {
                    return sum + (parseFloat(item.price) * item.quantity);
                }, 0).toFixed(2);
                
                generatePaymentQR(totalAmount);
                document.getElementById('payment-methods').classList.add('hidden');
                document.getElementById('qr-payment').classList.remove('hidden');
            });
            
            // 扫描付款码
            document.getElementById('scan-pay').addEventListener('click', () => {
                document.getElementById('payment-methods').classList.add('hidden');
                document.getElementById('scan-payment').classList.remove('hidden');
                paymentScanner.startScanner();
            });
            
            // 从收款码界面切换到扫描付款码界面
            document.getElementById('switch-to-scan-payment').addEventListener('click', () => {
                document.getElementById('qr-payment').classList.add('hidden');
                document.getElementById('scan-payment').classList.remove('hidden');
                paymentScanner.startScanner();
            });
            
            // 初始化付款扫描器 - 仅用于支付流程
            const paymentScanner = initScanner('payment-preview', (paymentCode) => {
                console.log('付款扫描器回调执行 - 处理支付，不执行页面跳转');
                if (!window.dataStore) {
                    console.error('dataStore未初始化');
                    return;
                }
                
                try {
                    // 模拟付款成功
                    showToast('付款成功', 'success');
                    paymentScanner.stopScanner();
                    document.getElementById('scan-payment').classList.add('hidden');
                    
                    // 创建订单
                    const order = window.dataStore.createOrder();
                    if (order) {
                        renderCart();
                        showToast(`订单创建成功: ${order.id}`, 'success');
                        updateHomeOverview();
                        // 添加TTS语音播报
                        if (window.ttsManager) {
                            window.ttsManager.speakPaymentSuccess(order.totalAmount, '微信');
                        }
                    }
                } catch (error) {
                    console.error('付款处理出错:', error);
                    showToast('付款处理失败，请重试', 'error');
                    paymentScanner.stopScanner();
                }
            });
            
            // 开始付款扫描
            document.getElementById('start-payment-scan').addEventListener('click', () => {
                paymentScanner.startScanner();
            });
            
            // 确认收款
            document.getElementById('confirm-payment').addEventListener('click', () => {
                if (!window.dataStore) {
                    console.error('dataStore未初始化');
                    return;
                }
                // 创建订单
                const order = window.dataStore.createOrder();
                if (order) {
                    document.getElementById('qr-payment').classList.add('hidden');
                    renderCart();
                    showToast(`收款成功，订单号: ${order.id}`, 'success');
                    updateHomeOverview();
                    // 添加TTS语音播报
                    if (window.ttsManager) {
                        // 获取当前选择的支付平台
                        const selectedPlatform = document.getElementById('select-wechat').classList.contains('bg-green-50') ? '微信' : '支付宝';
                        window.ttsManager.speakPaymentSuccess(order.totalAmount, selectedPlatform);
                    }
                }
            });
            
            // 导出商品数据
            document.getElementById('export-products').addEventListener('click', () => {
                if (!window.dataStore) {
                    console.error('dataStore未初始化');
                    return;
                }
                if (window.dataStore.products.length === 0) {
                    showToast('没有商品数据可导出', 'warning');
                    return;
                }
                
                const csv = window.dataStore.exportProductsToCSV();
                const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.setAttribute('href', url);
                a.setAttribute('download', `商品数据_${new Date().toLocaleDateString()}.csv`);
                a.style.visibility = 'hidden';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            });
            
            // 导出订单数据
            document.getElementById('export-orders').addEventListener('click', () => {
                if (!window.dataStore) {
                    console.error('dataStore未初始化');
                    return;
                }
                if (window.dataStore.orders.length === 0) {
                    showToast('没有订单数据可导出', 'warning');
                    return;
                }
                
                const csv = window.dataStore.exportOrdersToCSV();
                const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.setAttribute('href', url);
                a.setAttribute('download', `订单数据_${new Date().toLocaleDateString()}.csv`);
                a.style.visibility = 'hidden';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            });
            
            // 清除所有数据
            document.getElementById('clear-all-data').addEventListener('click', () => {
                if (!window.dataStore) {
                    console.error('dataStore未初始化');
                    return;
                }
                if (confirm('确定要清除所有数据吗？此操作不可恢复！')) {
                    window.dataStore.clearAllData();
                    renderProductList();
                    renderCart();
                    renderRecentOrders();
                    updateHomeOverview();
                    showToast('所有数据已清除', 'success');
                }
            });
            
            // 登录模态框
            const loginModal = `
            <div id="login-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
                <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6 transform transition-all">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="text-xl font-bold text-primary">用户登录</h3>
                        <button id="close-login-modal" class="text-gray-500 hover:text-gray-700">
                            <i class="fa fa-times text-xl"></i>
                        </button>
                    </div>
                    <form id="login-form" class="space-y-4">
                        <div>
                            <label for="login-username" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                            <input type="text" id="login-username" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition duration-200" placeholder="请输入用户名">
                            <p id="login-username-error" class="mt-1 text-sm text-red-600 hidden"></p>
                        </div>
                        <div>
                            <label for="login-password" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                            <input type="password" id="login-password" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition duration-200" placeholder="请输入密码">
                            <p id="login-password-error" class="mt-1 text-sm text-red-600 hidden"></p>
                        </div>
                        <div class="flex items-center">
                            <input type="checkbox" id="remember-me" class="h-4 w-4 text-primary border-gray-300 rounded focus:ring-primary">
                            <label for="remember-me" class="ml-2 block text-sm text-gray-700">记住我</label>
                        </div>
                        <button type="submit" class="w-full bg-primary text-white font-medium py-2 px-4 rounded-lg hover:bg-primary-dark transition duration-200 transform hover:scale-[1.02] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                            登录
                        </button>
                    </form>
                    <div class="mt-4 text-center">
                        <p class="text-gray-600">
                            还没有账号？<button id="switch-to-register" class="text-primary hover:text-primary-dark transition duration-200">立即注册</button>
                        </p>
                    </div>
                </div>
            </div>`;

            // 注册模态框
            const registerModal = `
            <div id="register-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
                <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6 transform transition-all">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="text-xl font-bold text-primary">用户注册</h3>
                        <button id="close-register-modal" class="text-gray-500 hover:text-gray-700">
                            <i class="fa fa-times text-xl"></i>
                        </button>
                    </div>
                    <form id="register-form" class="space-y-4">
                        <div>
                            <label for="register-username" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                            <input type="text" id="register-username" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition duration-200" placeholder="请设置用户名">
                            <p id="register-username-error" class="mt-1 text-sm text-red-600 hidden"></p>
                        </div>
                        <div>
                            <label for="register-email" class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                            <input type="email" id="register-email" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition duration-200" placeholder="请输入邮箱">
                            <p id="register-email-error" class="mt-1 text-sm text-red-600 hidden"></p>
                        </div>
                        <div>
                            <label for="register-password" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                            <input type="password" id="register-password" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition duration-200" placeholder="请设置密码">
                            <p id="register-password-error" class="mt-1 text-sm text-red-600 hidden"></p>
                        </div>
                        <div>
                            <label for="register-confirm-password" class="block text-sm font-medium text-gray-700 mb-1">确认密码</label>
                            <input type="password" id="register-confirm-password" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition duration-200" placeholder="请再次输入密码">
                            <p id="register-confirm-password-error" class="mt-1 text-sm text-red-600 hidden"></p>
                        </div>
                        <button type="submit" class="w-full bg-primary text-white font-medium py-2 px-4 rounded-lg hover:bg-primary-dark transition duration-200 transform hover:scale-[1.02] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                            注册
                        </button>
                    </form>
                    <div class="mt-4 text-center">
                        <p class="text-gray-600">
                            已有账号？<button id="switch-to-login" class="text-primary hover:text-primary-dark transition duration-200">立即登录</button>
                        </p>
                    </div>
                </div>
            </div>`;

            // 添加模态框到页面
            document.body.insertAdjacentHTML('beforeend', loginModal);
            document.body.insertAdjacentHTML('beforeend', registerModal);

            // 用户认证相关函数
            const authManager = {
                // 检查登录状态
                checkLoginStatus: function() {
                    const user = localStorage.getItem('currentUser');
                    if (user) {
                        const parsedUser = JSON.parse(user);
                        document.getElementById('current-user').textContent = parsedUser.username;
                        document.getElementById('login-btn').classList.add('hidden');
                        document.getElementById('register-btn').classList.add('hidden');
                        // 添加登出按钮
                        const logoutBtn = document.createElement('button');
                        logoutBtn.id = 'logout-btn';
                        logoutBtn.className = 'btn-secondary px-4 py-2 rounded-lg hover:shadow-md transition-all transform hover:-translate-y-0.5 flex-1 md:flex-none';
                        logoutBtn.innerHTML = '<i class="fa fa-sign-out-alt mr-1"></i> 登出';
                        logoutBtn.addEventListener('click', function() {
                            localStorage.removeItem('currentUser');
                            location.reload();
                        });
                        document.getElementById('auth-actions').appendChild(logoutBtn);
                    }
                },

                // 登录
                login: function(username, password) {
                    // 模拟登录验证（实际应用中应该调用API）
                    if (username && password) {
                        const user = {
                            id: Date.now(),
                            username: username,
                            email: username + '@example.com' // 模拟数据
                        };
                        localStorage.setItem('currentUser', JSON.stringify(user));
                        this.checkLoginStatus();
                        return true;
                    }
                    return false;
                },

                // 注册
                register: function(username, email, password) {
                    // 模拟注册（实际应用中应该调用API）
                    if (username && email && password) {
                        // 存储用户信息（实际应用中应该由服务器返回）
                        const user = {
                            id: Date.now(),
                            username: username,
                            email: email
                        };
                        return true;
                    }
                    return false;
                }
            };

            // 表单验证函数
            function validateForm(formId, fields) {
                let isValid = true;
                
                fields.forEach(field => {
                    const element = document.getElementById(field.id);
                    const errorElement = document.getElementById(`${field.id}-error`);
                    
                    // 清除之前的错误
                    if (errorElement) {
                        errorElement.classList.add('hidden');
                    }
                    if (element) {
                        element.classList.remove('border-red-500');
                    }

                    // 验证必填字段
                    if (field.required && element && !element.value.trim()) {
                        if (errorElement) {
                            errorElement.textContent = field.requiredMessage;
                            errorElement.classList.remove('hidden');
                        }
                        if (element) {
                            element.classList.add('border-red-500');
                        }
                        isValid = false;
                        return;
                    }

                    // 验证邮箱格式
                    if (field.type === 'email' && element && element.value.trim()) {
                        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                        if (!emailRegex.test(element.value.trim())) {
                            if (errorElement) {
                                errorElement.textContent = field.emailMessage || '请输入有效的邮箱地址';
                                errorElement.classList.remove('hidden');
                            }
                            if (element) {
                                element.classList.add('border-red-500');
                            }
                            isValid = false;
                            return;
                        }
                    }

                    // 验证密码长度
                    if (field.type === 'password' && element && element.value) {
                        if (element.value.length < 6) {
                            if (errorElement) {
                                errorElement.textContent = field.passwordLengthMessage || '密码长度至少为6位';
                                errorElement.classList.remove('hidden');
                            }
                            if (element) {
                                element.classList.add('border-red-500');
                            }
                            isValid = false;
                            return;
                        }
                    }

                    // 验证两次密码是否一致
                    if (field.confirmWith) {
                        const confirmField = document.getElementById(field.confirmWith);
                        if (element && confirmField && element.value !== confirmField.value) {
                            if (errorElement) {
                                errorElement.textContent = field.confirmMessage || '两次输入的密码不一致';
                                errorElement.classList.remove('hidden');
                            }
                            if (element) {
                                element.classList.add('border-red-500');
                            }
                            isValid = false;
                            return;
                        }
                    }
                });

                return isValid;
            }

            // 登录按钮点击事件
            document.getElementById('login-btn').addEventListener('click', () => {
                document.getElementById('login-modal').classList.remove('hidden');
            });

            // 注册按钮点击事件
            document.getElementById('register-btn').addEventListener('click', () => {
                document.getElementById('register-modal').classList.remove('hidden');
            });

            // 关闭登录模态框
            document.getElementById('close-login-modal').addEventListener('click', () => {
                document.getElementById('login-modal').classList.add('hidden');
            });

            // 关闭注册模态框
            document.getElementById('close-register-modal').addEventListener('click', () => {
                document.getElementById('register-modal').classList.add('hidden');
            });

            // 切换到注册
            document.getElementById('switch-to-register').addEventListener('click', () => {
                document.getElementById('login-modal').classList.add('hidden');
                document.getElementById('register-modal').classList.remove('hidden');
            });

            // 切换到登录
            document.getElementById('switch-to-login').addEventListener('click', () => {
                document.getElementById('register-modal').classList.add('hidden');
                document.getElementById('login-modal').classList.remove('hidden');
            });

            // 登录表单提交
            document.getElementById('login-form').addEventListener('submit', (e) => {
                e.preventDefault();
                
                const isValid = validateForm('login-form', [
                    {
                        id: 'login-username',
                        required: true,
                        requiredMessage: '请输入用户名'
                    },
                    {
                        id: 'login-password',
                        required: true,
                        requiredMessage: '请输入密码',
                        type: 'password'
                    }
                ]);

                if (isValid) {
                    const username = document.getElementById('login-username').value;
                    const password = document.getElementById('login-password').value;
                    const rememberMe = document.getElementById('remember-me').checked;

                    if (authManager.login(username, password)) {
                        document.getElementById('login-modal').classList.add('hidden');
                        showToast('登录成功', 'success');
                        // 清空表单
                        document.getElementById('login-form').reset();
                    } else {
                        showToast('用户名或密码错误', 'error');
                    }
                }
            });

            // 注册表单提交
            document.getElementById('register-form').addEventListener('submit', (e) => {
                e.preventDefault();
                
                const isValid = validateForm('register-form', [
                    {
                        id: 'register-username',
                        required: true,
                        requiredMessage: '请设置用户名'
                    },
                    {
                        id: 'register-email',
                        required: true,
                        requiredMessage: '请输入邮箱',
                        type: 'email'
                    },
                    {
                        id: 'register-password',
                        required: true,
                        requiredMessage: '请设置密码',
                        type: 'password'
                    },
                    {
                        id: 'register-confirm-password',
                        required: true,
                        requiredMessage: '请确认密码',
                        confirmWith: 'register-password'
                    }
                ]);

                if (isValid) {
                    const username = document.getElementById('register-username').value;
                    const email = document.getElementById('register-email').value;
                    const password = document.getElementById('register-password').value;

                    if (authManager.register(username, email, password)) {
                        document.getElementById('register-modal').classList.add('hidden');
                        showToast('注册成功，请登录', 'success');
                        // 清空表单
                        document.getElementById('register-form').reset();
                    } else {
                        showToast('注册失败，请重试', 'error');
                    }
                }
            });

            // 页面加载时检查登录状态
            authManager.checkLoginStatus();
            
            // 商户认证按钮点击事件
            document.getElementById('verify-merchant-btn').addEventListener('click', () => {
                // 创建并显示商户认证模态框
                const modal = document.createElement('div');
                modal.id = 'merchant-verification-modal';
                modal.className = 'fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center';
                modal.innerHTML = `
                    <div class="bg-white rounded-lg shadow-lg w-full max-w-md mx-4 p-6 animate-fade-in">
                        <div class="flex justify-between items-center mb-4">
                            <h3 class="text-xl font-bold">商户认证</h3>
                            <button id="close-verification-modal" class="text-gray-500 hover:text-gray-700">
                                <i class="fa fa-times text-xl"></i>
                            </button>
                        </div>
                        <div class="space-y-4">
                            <div>
                                <label class="block text-gray-700 mb-2">商户名称</label>
                                <input type="text" id="merchant-name" class="w-full px-3 py-2 border border-gray-300 rounded-lg" placeholder="请输入商户名称">
                            </div>
                            <div>
                                <label class="block text-gray-700 mb-2">联系人姓名</label>
                                <input type="text" id="contact-name" class="w-full px-3 py-2 border border-gray-300 rounded-lg" placeholder="请输入联系人姓名">
                            </div>
                            <div>
                                <label class="block text-gray-700 mb-2">联系电话</label>
                                <input type="tel" id="contact-phone" class="w-full px-3 py-2 border border-gray-300 rounded-lg" placeholder="请输入联系电话">
                            </div>
                            <div>
                                <label class="block text-gray-700 mb-2">营业执照照片</label>
                                <input type="file" id="business-license" accept="image/*" class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                                <p class="text-xs text-gray-500 mt-1">支持JPG、PNG格式，文件大小不超过5MB</p>
                            </div>
                            <div>
                                <label class="block text-gray-700 mb-2">身份证照片（正面）</label>
                                <input type="file" id="id-card-front" accept="image/*" class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                            </div>
                            <div>
                                <label class="block text-gray-700 mb-2">身份证照片（反面）</label>
                                <input type="file" id="id-card-back" accept="image/*" class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                            </div>
                            <div class="pt-2">
                                <button id="submit-verification" class="btn-primary w-full">
                                    <i class="fa fa-check mr-1"></i> 提交认证申请
                                </button>
                            </div>
                        </div>
                    </div>
                `;
                document.body.appendChild(modal);
                
                // 关闭模态框
                document.getElementById('close-verification-modal').addEventListener('click', () => {
                    document.body.removeChild(modal);
                });
                
                // 点击模态框外部关闭
                modal.addEventListener('click', (e) => {
                    if (e.target === modal) {
                        document.body.removeChild(modal);
                    }
                });
                
                // 提交认证申请
                document.getElementById('submit-verification').addEventListener('click', () => {
                    // 这里仅实现前端验证，实际应用中需要调用后端API
                    const merchantName = document.getElementById('merchant-name').value;
                    const contactName = document.getElementById('contact-name').value;
                    const contactPhone = document.getElementById('contact-phone').value;
                    
                    if (!merchantName || !contactName || !contactPhone) {
                        showToast('请填写完整的认证信息', 'warning');
                        return;
                    }
                    
                    // 模拟提交成功
                    showToast('认证申请已提交，请等待审核', 'info');
                    
                    // 更新认证状态为"审核中"
                    document.getElementById('verification-status').textContent = '审核中';
                    document.getElementById('verification-status').className = 'text-yellow-500';
                    
                    document.body.removeChild(modal);
                });
            });
            
            // 简化的支付流程 - 微信收款按钮事件
            document.getElementById('wechat-qr-btn').addEventListener('click', async () => {
                // 获取当前订单总金额
                const order = window.dataStore.getCart();
                const totalAmount = order.totalAmount.toFixed(2);
                
                // 如果金额为0，提示用户
                if (order.totalAmount <= 0) {
                    showToast('请先添加商品', 'warning');
                    return;
                }
                
                try {
                    // 尝试跳转到微信原生收款界面
                    const success = await window.paymentManager.openNativePaymentScreen('wechat', totalAmount);
                    
                    // 如果跳转成功，显示提示；如果跳转失败，显示本地收款码
                    if (!success) {
                        showToast('显示本地收款码', 'info');
                        showPaymentQRCode('wechat', totalAmount);
                    }
                } catch (error) {
                    console.error('微信收款失败:', error);
                    showToast('微信收款失败，请重试', 'error');
                    showPaymentQRCode('wechat', totalAmount);
                }
            });
            
            // 简化的支付流程 - 支付宝收款按钮事件
            document.getElementById('alipay-qr-btn').addEventListener('click', async () => {
                // 获取当前订单总金额
                const order = window.dataStore.getCart();
                const totalAmount = order.totalAmount.toFixed(2);
                
                // 如果金额为0，提示用户
                if (order.totalAmount <= 0) {
                    showToast('请先添加商品', 'warning');
                    return;
                }
                
                try {
                    // 尝试跳转到支付宝原生收款界面
                    const success = await window.paymentManager.openNativePaymentScreen('alipay', totalAmount);
                    
                    // 如果跳转成功，显示提示；如果跳转失败，显示本地收款码
                    if (!success) {
                        showToast('显示本地收款码', 'info');
                        showPaymentQRCode('alipay', totalAmount);
                    }
                } catch (error) {
                    console.error('支付宝收款失败:', error);
                    showToast('支付宝收款失败，请重试', 'error');
                    showPaymentQRCode('alipay', totalAmount);
                }
            });
            
            // 简化的支付流程 - 扫描付款码按钮事件
            document.getElementById('scan-payment-btn').addEventListener('click', async () => {
                // 获取当前订单总金额
                const order = window.dataStore.getCart();
                
                // 如果金额为0，提示用户
                if (order.totalAmount <= 0) {
                    showToast('请先添加商品', 'warning');
                    return;
                }
                
                try {
                    // 检查是否有原生接口可以调用
                    if (window.NativeInterface) {
                        // 创建选择支付方式的对话框
                        const paymentMethod = confirm('请选择支付方式\n- 确定: 微信\n- 取消: 支付宝');
                        
                        try {
                            if (paymentMethod) {
                                // 调用原生接口打开微信扫码
                                window.NativeInterface.openWechatScan(order.totalAmount.toString());
                            } else {
                                // 调用原生接口打开支付宝扫码，并带上金额参数
                                window.NativeInterface.openAlipayScan(order.totalAmount.toString());
                            }
                            
                            // 记录当前待支付订单信息，用于处理支付结果
                            if (window.dataStore) {
                                const newOrder = window.dataStore.createOrder();
                                if (newOrder) {
                                    currentPaymentOrderId = newOrder.id;
                                    currentPaymentAmount = newOrder.totalAmount;
                                    showToast('请使用' + (paymentMethod ? '微信' : '支付宝') + '扫码收款', 'info');
                                }
                            }
                        } catch (nativeError) {
                            console.error('调用原生扫码接口失败:', nativeError);
                            showToast('调用扫码功能失败，显示收款码', 'error');
                            // 原生接口调用失败时，显示收款二维码作为兜底方案
                            showPaymentQRCode(paymentMethod ? 'wechat' : 'alipay', order.totalAmount.toString());
                        }
                    } else {
                        // 如果没有原生接口，直接使用上传的收款二维码作为兜底方案
                        const paymentMethod = confirm('请选择支付方式\n- 确定: 微信\n- 取消: 支付宝');
                        showPaymentQRCode(paymentMethod ? 'wechat' : 'alipay', order.totalAmount.toString());
                    }
                } catch (error) {
                    console.error('支付处理失败:', error);
                    showToast('支付处理失败，请重试', 'error');
                }
            });
            
            // 返回按钮事件
            document.getElementById('back-to-payment').addEventListener('click', () => {
                document.getElementById('payment-qr-display').classList.add('hidden');
            });
            
            // 确认收款按钮事件
            document.getElementById('confirm-qr-payment').addEventListener('click', () => {
                try {
                    // 创建订单
                    const order = window.dataStore.createOrder();
                    if (order) {
                        renderCart();
                        showToast(`订单创建成功: ${order.id}`, 'success');
                        updateHomeOverview();
                        
                        // 添加TTS语音播报
                        if (window.ttsManager) {
                            window.ttsManager.speakPaymentSuccess(order.totalAmount, '微信');
                        }
                        
                        // 隐藏支付界面
                        document.getElementById('payment-qr-display').classList.add('hidden');
                    }
                } catch (error) {
                    console.error('确认收款失败:', error);
                    showToast('确认收款失败，请重试', 'error');
                }
            });
            
            // 显示支付二维码的辅助函数
            function showPaymentQRCode(platform, amount) {
                if (!window.paymentManager) {
                    console.error('paymentManager未初始化');
                    return;
                }
                
                // 显示收款码界面
                document.getElementById('payment-qr-display').classList.remove('hidden');
                
                // 设置平台名称和金额
                document.getElementById('payment-platform-name').textContent = platform === 'wechat' ? '微信收款' : '支付宝收款';
                document.getElementById('payment-qr-amount').textContent = `¥${amount}`;
                
                // 使用paymentManager生成带金额的收款码
                const success = window.paymentManager.generatePaymentQRCode(platform, parseFloat(amount));
                
                // 如果生成失败，显示上传的收款码图片作为备选
                if (!success) {
                    showToast('生成收款码失败，显示上传的收款码', 'warning');
                    const config = window.paymentManager.getPaymentConfig();
                    const qrImageElement = document.getElementById('payment-qr-image');
                    
                    if (platform === 'wechat' && config.wechat && config.wechat.image) {
                        qrImageElement.src = config.wechat.image;
                    } else if (platform === 'alipay' && config.alipay && config.alipay.image) {
                        qrImageElement.src = config.alipay.image;
                    } else {
                        // 如果没有上传图片，显示提示
                        qrImageElement.src = '';
                        qrImageElement.alt = '请先上传收款码图片';
                        showToast('请先在设置中上传收款码图片', 'error');
                    }
                }
            }
            
            // 添加保存支付配置按钮的事件监听器
            if (document.getElementById('save-payment-config')) {
                document.getElementById('save-payment-config').addEventListener('click', () => {
                    if (!window.paymentManager) {
                        console.error('paymentManager未初始化');
                        showToast('支付管理模块未加载', 'error');
                        return;
                    }
                    
                    // 获取微信支付配置
                    const wechatEnabled = document.getElementById('wechat-enabled')?.checked || false;
                    const wechatImage = document.getElementById('wechat-image-preview')?.src || '';
                    
                    // 获取支付宝支付配置
                    const alipayEnabled = document.getElementById('alipay-enabled')?.checked || false;
                    const alipayImage = document.getElementById('alipay-image-preview')?.src || '';
                    
                    // 保存配置
                    window.paymentManager.savePaymentConfig({
                        wechat: {
                            enabled: wechatEnabled,
                            image: wechatImage,
                            link: ''
                        },
                        alipay: {
                            enabled: alipayEnabled,
                            image: alipayImage,
                            link: ''
                        }
                    });
                    
                    showToast('支付配置已保存', 'success');
                });
            }
            
            // 添加收款码图片上传的事件监听器
            if (document.getElementById('wechat-qr-image')) {
                document.getElementById('wechat-qr-image').addEventListener('change', function(e) {
                    if (e.target.files && e.target.files[0]) {
                        const reader = new FileReader();
                        reader.onload = function(e) {
                            // 显示预览
                            if (document.getElementById('wechat-image-preview')) {
                                document.getElementById('wechat-image-preview').classList.remove('hidden');
                                if (document.getElementById('wechat-qr-preview')) {
                                    document.getElementById('wechat-qr-preview').src = e.target.result;
                                }
                            }
                        }
                        reader.readAsDataURL(e.target.files[0]);
                    }
                });
            }
            
            if (document.getElementById('alipay-qr-image')) {
                document.getElementById('alipay-qr-image').addEventListener('change', function(e) {
                    if (e.target.files && e.target.files[0]) {
                        const reader = new FileReader();
                        reader.onload = function(e) {
                            // 显示预览
                            if (document.getElementById('alipay-image-preview')) {
                                document.getElementById('alipay-image-preview').classList.remove('hidden');
                                if (document.getElementById('alipay-qr-preview')) {
                                    document.getElementById('alipay-qr-preview').src = e.target.result;
                                }
                            }
                        }
                        reader.readAsDataURL(e.target.files[0]);
                    }
                });
            }
            
            // 初始化支付配置
            function initPaymentConfig() {
                if (!window.paymentManager) {
                    console.error('paymentManager未初始化');
                    return;
                }
                
                const config = window.paymentManager.getPaymentConfig();
                
                // 初始化微信配置
                if (config.wechat) {
                    if (document.getElementById('wechat-enabled')) {
                        document.getElementById('wechat-enabled').checked = config.wechat.enabled;
                    }
                    if (document.getElementById('wechat-image')) {
                        document.getElementById('wechat-image').value = config.wechat.image || '';
                    }
                    if (document.getElementById('wechat-link')) {
                        document.getElementById('wechat-link').value = config.wechat.link || '';
                    }
                    
                    if (config.wechat.image && document.getElementById('wechat-image-preview')) {
                        document.getElementById('wechat-image-preview').src = config.wechat.image;
                        document.getElementById('wechat-image-preview').style.display = 'block';
                    }
                }
                
                // 初始化支付宝配置
                if (config.alipay) {
                    if (document.getElementById('alipay-enabled')) {
                        document.getElementById('alipay-enabled').checked = config.alipay.enabled;
                    }
                    if (document.getElementById('alipay-image')) {
                        document.getElementById('alipay-image').value = config.alipay.image || '';
                    }
                    if (document.getElementById('alipay-link')) {
                        document.getElementById('alipay-link').value = config.alipay.link || '';
                    }
                    
                    if (config.alipay.image && document.getElementById('alipay-image-preview')) {
                        document.getElementById('alipay-image-preview').src = config.alipay.image;
                        document.getElementById('alipay-image-preview').style.display = 'block';
                    }
                }
            }
            
            // 扫描客户付款码按钮点击事件
            if (document.getElementById('scan-payment-btn')) {
                document.getElementById('scan-payment-btn').addEventListener('click', () => {
                    const transactionAmountElement = document.getElementById('transaction-amount');
                    if (!transactionAmountElement) {
                        showToast('请输入有效的交易金额', 'warning');
                        return;
                    }
                    
                    const amount = transactionAmountElement.value;
                    if (!amount || parseFloat(amount) <= 0) {
                        showToast('请输入有效的交易金额', 'warning');
                        return;
                    }
                    
                    showToast('付款码扫描功能开发中', 'info');
                    // 后续可以实现付款码扫描界面
                });
            }
            
            // 生成同步码按钮点击事件
            if (document.getElementById('generate-sync-code-btn')) {
                document.getElementById('generate-sync-code-btn').addEventListener('click', () => {
                    // 先声明变量，确保在整个函数中的作用域
                    let syncCode = '';
                    let syncCodeElement = null;
                    
                    try {
                        console.log('开始生成同步码...');
                        
                        // 生成包含时间戳的同步码
                        const timestamp = Date.now();
                        const randomPart = Math.floor(Math.random() * 1000000);
                        syncCode = `${timestamp}-${randomPart}`;
                        
                        // 准备同步数据
                        const syncData = {
                            timestamp: timestamp,
                            syncCode: syncCode,
                            products: window.dataStore ? window.dataStore.products : [],
                            orders: window.dataStore ? window.dataStore.orders : [],
                            version: '1.0'
                        };
                        
                        // 保存同步数据到localStorage
                        try {
                            localStorage.setItem('syncData', JSON.stringify(syncData));
                            console.log('同步数据已保存到localStorage');
                        } catch (storageError) {
                            console.error('保存同步数据失败:', storageError);
                            showToast('保存同步数据失败，可能是存储空间不足', 'warning');
                        }
                        
                        // 创建同步码元素
                        syncCodeElement = document.createElement('div');
                        syncCodeElement.className = 'text-center';
                        
                        // 生成二维码（使用本地二维码生成库）
                        if (typeof generateOfflineQRCode === 'function') {
                            console.log('调用generateOfflineQRCode函数生成二维码');
                            
                            // 创建加载指示器
                            const loadingIndicator = document.createElement('div');
                            loadingIndicator.className = 'w-48 h-48 mx-auto mb-4 flex items-center justify-center bg-gray-50 rounded-lg';
                            loadingIndicator.innerHTML = '<i class="fa fa-spinner fa-spin text-2xl text-gray-500"></i>';
                            syncCodeElement.appendChild(loadingIndicator);
                            
                            // 使用与支付二维码相同的库生成同步码二维码
                            // 注意：generateOfflineQRCode返回的是Promise对象
                            generateOfflineQRCode(syncCode).then(qrCodeUrl => {
                                // 移除加载指示器
                                syncCodeElement.removeChild(loadingIndicator);
                                
                                if (qrCodeUrl && typeof qrCodeUrl === 'string') {
                                    console.log('二维码生成成功:', qrCodeUrl.substring(0, 50) + '...');
                                    
                                    // 创建二维码和文本的容器
                                    const qrContainer = document.createElement('div');
                                    qrContainer.className = 'flex flex-col items-center';
                                    
                                    // 添加二维码图片
                                    const qrImg = document.createElement('img');
                                    qrImg.src = qrCodeUrl;
                                    qrImg.id = 'sync-qr-code';
                                    qrImg.className = 'mx-auto mb-4';
                                    qrImg.width = 240;
                                    qrImg.height = 240;
                                    qrContainer.appendChild(qrImg);
                                    
                                    // 添加文本元素
                                    const codeTextElement = document.createElement('p');
                                    codeTextElement.className = 'font-mono text-sm text-gray-600 mb-4 px-4 break-all';
                                    codeTextElement.textContent = syncCode;
                                    qrContainer.appendChild(codeTextElement);
                                    
                                    syncCodeElement.appendChild(qrContainer);
                                } else {
                                    console.error('二维码生成失败，使用回退方案');
                                    // 回退方案：如果二维码生成失败，显示文本
                                    const fallbackDiv = document.createElement('div');
                                    fallbackDiv.className = 'w-48 h-48 mx-auto mb-4 bg-white p-2 border border-gray-200 rounded-lg';
                                    fallbackDiv.innerHTML = `
                                        <div class="flex items-center justify-center h-full">
                                            <div class="text-sm font-mono">${syncCode}</div>
                                        </div>
                                    `;
                                    syncCodeElement.appendChild(fallbackDiv);
                                }
                            }).catch(error => {
                                // 移除加载指示器
                                if (loadingIndicator.parentNode === syncCodeElement) {
                                    syncCodeElement.removeChild(loadingIndicator);
                                }
                                
                                console.error('生成二维码时出错:', error);
                                // 回退方案：出错时显示文本
                                const fallbackDiv = document.createElement('div');
                                fallbackDiv.className = 'w-48 h-48 mx-auto mb-4 bg-white p-2 border border-gray-200 rounded-lg';
                                fallbackDiv.innerHTML = `
                                    <div class="flex items-center justify-center h-full">
                                        <div class="text-sm font-mono">${syncCode}</div>
                                    </div>
                                `;
                                syncCodeElement.appendChild(fallbackDiv);
                            });
                        } else {
                            console.error('generateOfflineQRCode函数不存在，使用回退方案');
                            // 回退方案：如果没有二维码生成函数，显示文本
                            const fallbackDiv = document.createElement('div');
                            fallbackDiv.className = 'w-48 h-48 mx-auto mb-4 bg-white p-2 border border-gray-200 rounded-lg';
                            fallbackDiv.innerHTML = `
                                <div class="flex items-center justify-center h-full">
                                    <div class="text-sm font-mono">${syncCode}</div>
                                </div>
                            `;
                            syncCodeElement.appendChild(fallbackDiv);
                        }
                    } catch (error) {
                        console.error('生成同步码时出现严重错误:', error);
                        showToast('生成同步码失败，请刷新页面后重试', 'error');
                    }
                    
                    // 确保syncCodeElement已正确初始化
                    if (!syncCodeElement) {
                        console.error('syncCodeElement未正确初始化');
                        return;
                    }
                    
                    // 文本元素已在二维码容器中创建，此处不再重复创建
                    
                    // 创建使用说明元素
                    const instructionDiv = document.createElement('div');
                    instructionDiv.className = 'bg-blue-50 p-3 rounded-lg text-left text-sm text-gray-700 mb-4';
                    instructionDiv.innerHTML = '<p class="mb-2"><i class="fa fa-info-circle text-primary mr-1"></i> 使用说明：</p><ol class="list-decimal pl-5 space-y-1"><li>在另一台设备上打开收银系统</li><li>点击"扫描同步码"按钮</li><li>扫描左侧显示的二维码</li></ol>';
                    syncCodeElement.appendChild(instructionDiv);
                    
                    // 添加有效期提示
                    const validityElement = document.createElement('div');
                    validityElement.className = 'space-y-2';
                    const validityText = document.createElement('span');
                    validityText.className = 'text-xs text-gray-500';
                    validityText.textContent = '同步码有效期：5分钟';
                    validityElement.appendChild(validityText);
                    syncCodeElement.appendChild(validityElement);
                    
                    // 显示同步码对话框
                    showModal('多设备同步 - 生成同步码', syncCodeElement);
                    showToast('同步码已生成，请在其他设备上扫描', 'success');
                    recordSyncHistory('生成同步码', `生成了新的同步码`);
                    
                    // 5分钟后清除同步数据
                    setTimeout(() => {
                        const existingData = localStorage.getItem('syncData');
                        if (existingData) {
                            const parsedData = JSON.parse(existingData);
                            if (parsedData.syncCode === syncCode) {
                                localStorage.removeItem('syncData');
                                // 如果模态框还开着，显示过期提示
                                const modal = document.getElementById('custom-modal');
                                if (modal && modal.querySelector('#sync-qr-code')) {
                                    showToast('同步码已过期，请重新生成', 'error');
                                }
                            }
                        }
                    }, 5 * 60 * 1000);
                });
            }
            
            // 扫描同步码按钮点击事件
            if (document.getElementById('scan-sync-code-btn')) {
                document.getElementById('scan-sync-code-btn').addEventListener('click', () => {
                    // 创建扫描界面
                    const scanElement = document.createElement('div');
                    scanElement.className = 'space-y-4';
                    
                    // 添加视频元素用于扫描
                    const videoContainer = document.createElement('div');
                    videoContainer.className = 'relative bg-black rounded-lg overflow-hidden';
                    
                    // 创建视频元素
                    const videoElement = document.createElement('video');
                    videoElement.id = 'sync-scanner-preview';
                    videoElement.className = 'w-full aspect-video object-cover';
                    videoElement.autoplay = true;
                    videoElement.playsInline = true;
                    
                    // 创建扫描框指示（使用与收银和添加商品页面相同的样式）
                    const scanIndicator = document.createElement('div');
                    scanIndicator.className = 'absolute inset-0 flex items-center justify-center';
                    
                    const scanBox = document.createElement('div');
                    scanBox.className = 'scan-box w-3/4 aspect-video flex items-center justify-center relative';
                    
                    // 添加四角装饰元素
                    const corner1 = document.createElement('div');
                    corner1.className = 'absolute top-0 left-0 w-8 h-8 border-t-4 border-l-4 border-secondary';
                    scanBox.appendChild(corner1);
                    
                    const corner2 = document.createElement('div');
                    corner2.className = 'absolute top-0 right-0 w-8 h-8 border-t-4 border-r-4 border-secondary';
                    scanBox.appendChild(corner2);
                    
                    const corner3 = document.createElement('div');
                    corner3.className = 'absolute bottom-0 left-0 w-8 h-8 border-b-4 border-l-4 border-secondary';
                    scanBox.appendChild(corner3);
                    
                    const corner4 = document.createElement('div');
                    corner4.className = 'absolute bottom-0 right-0 w-8 h-8 border-b-4 border-r-4 border-secondary';
                    scanBox.appendChild(corner4);
                    
                    // 添加扫描线
                    const scanLine = document.createElement('div');
                    scanLine.className = 'w-full h-1 bg-secondary animate-pulse';
                    scanBox.appendChild(scanLine);
                    
                    scanIndicator.appendChild(scanBox);
                    
                    videoContainer.appendChild(videoElement);
                    videoContainer.appendChild(scanIndicator);
                    
                    scanElement.appendChild(videoContainer);
                    scanElement.innerHTML += `
                        <div class="bg-blue-50 p-3 rounded-lg text-left text-sm text-gray-700">
                            <p class="mb-2"><i class="fa fa-info-circle text-primary mr-1"></i> 扫描说明：</p>
                            <ol class="list-decimal pl-5 space-y-1">
                                <li>将摄像头对准另一台设备上的同步码</li>
                                <li>系统将自动识别并同步数据</li>
                                <li>同步完成后会显示成功提示</li>
                            </ol>
                        </div>
                        <div class="space-y-2">
                            <button id="cancel-sync-scan" class="btn-secondary w-full">
                                <i class="fa fa-times mr-1"></i> 取消
                            </button>
                        </div>
                    `;
                    
                    // 显示扫描对话框
                    showModal('多设备同步 - 扫描同步码', scanElement);
                    
                    // 初始化扫描器
                    const syncScanner = initScanner('sync-scanner-preview', async (syncCode) => {
                        // 扫描到同步码后，停止扫描
                        syncScanner.stopScanner();
                        
                        // 查找本地存储中的同步数据
                        const syncDataJson = localStorage.getItem('syncData');
                        
                        if (syncDataJson) {
                            try {
                                const syncData = JSON.parse(syncDataJson);
                                
                                // 验证同步码是否匹配
                                if (syncData.syncCode === syncCode) {
                                    // 检查同步码是否过期
                                    const now = Date.now();
                                    const syncTime = syncData.timestamp;
                                    const timeDiff = now - syncTime;
                                    
                                    if (timeDiff > 5 * 60 * 1000) { // 5分钟过期
                                        showToast('同步码已过期，请重新生成', 'error');
                                        return;
                                    }
                                    
                                    // 开始同步数据
                                    await performDataSync(syncData);
                                    
                                    // 关闭模态框
                                    const modal = document.getElementById('custom-modal');
                                    if (modal) {
                                        document.body.removeChild(modal);
                                    }
                                } else {
                                    showToast('无效的同步码', 'error');
                                }
                            } catch (error) {
                                console.error('同步数据解析失败:', error);
                                showToast('同步数据解析失败', 'error');
                            }
                        } else {
                            showToast('未找到同步数据，请先生成同步码', 'error');
                        }
                    });
                    
                    // 启动扫描器
                    syncScanner.startScanner().catch(error => {
                        console.error('扫描器启动失败:', error);
                        showToast('无法访问摄像头，请检查权限', 'error');
                    });
                    
                    // 取消扫描按钮
                    document.getElementById('cancel-sync-scan').addEventListener('click', () => {
                        syncScanner.stopScanner();
                        const modal = document.getElementById('custom-modal');
                        if (modal) {
                            document.body.removeChild(modal);
                        }
                    });
                });
            }
            
            // 自动同步开关
            if (document.getElementById('auto-sync-toggle')) {
                document.getElementById('auto-sync-toggle').addEventListener('change', function() {
                    const isChecked = this.checked;
                    localStorage.setItem('autoSyncEnabled', isChecked);
                    showToast(isChecked ? '已开启自动同步' : '已关闭自动同步', 'info');
                });
                
                // 加载保存的设置
                const autoSyncEnabled = localStorage.getItem('autoSyncEnabled') === 'true';
                document.getElementById('auto-sync-toggle').checked = autoSyncEnabled;
            }
            
            // 同步选项开关
            const toggleSwitches = ['sync-products-toggle', 'sync-orders-toggle'];
            toggleSwitches.forEach(toggleId => {
                if (document.getElementById(toggleId)) {
                    // 加载保存的设置
                    const isChecked = localStorage.getItem(toggleId) !== 'false'; // 默认开启
                    document.getElementById(toggleId).checked = isChecked;
                    
                    // 添加事件监听器
                    document.getElementById(toggleId).addEventListener('change', function() {
                        localStorage.setItem(toggleId, this.checked);
                    });
                }
            });
            
            // 查看同步历史按钮
            if (document.getElementById('view-sync-history-btn')) {
                document.getElementById('view-sync-history-btn').addEventListener('click', () => {
                    showSyncHistory();
                });
            }
            
            // 初始化同步功能
            function initSyncFeatures() {
                // 检查是否已启用自动同步
                const autoSyncEnabled = localStorage.getItem('autoSyncEnabled') === 'true';
                if (autoSyncEnabled) {
                    // 每30分钟自动同步一次
                    setInterval(() => {
                        checkForAutoSync();
                    }, 30 * 60 * 1000);
                }
                
                // 更新同步状态显示
                updateSyncStatus();
            }
            
            // 检查是否需要自动同步
            function checkForAutoSync() {
                // 这里可以实现与服务器的通信，检查是否有新的数据需要同步
                // 简化版：只显示提示
                showToast('正在检查同步数据...', 'info');
            }
            
            // 更新同步状态显示
            function updateSyncStatus() {
                const syncStatus = document.getElementById('sync-status');
                const lastSyncTime = localStorage.getItem('lastSyncTime');
                
                if (syncStatus) {
                    if (lastSyncTime) {
                        syncStatus.textContent = '已同步';
                        syncStatus.className = 'text-green-600 font-semibold';
                        
                        const lastSyncElement = document.getElementById('last-sync-time');
                        if (lastSyncElement) {
                            lastSyncElement.textContent = `(上次同步: ${lastSyncTime})`;
                        }
                    } else {
                        syncStatus.textContent = '未同步';
                        syncStatus.className = 'text-gray-600 font-semibold';
                    }
                }
            }
            
            // 保存同步状态
            function saveSyncStatus(success) {
                if (success) {
                    const now = new Date();
                    const formattedTime = now.toLocaleString('zh-CN', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit'
                    });
                    localStorage.setItem('lastSyncTime', formattedTime);
                }
                updateSyncStatus();
            }
            
            // 记录同步历史
            function recordSyncHistory(action, details) {
                try {
                    const history = JSON.parse(localStorage.getItem('syncHistory') || '[]');
                    const now = new Date();
                    
                    // 只保留最近50条记录
                    if (history.length >= 50) {
                        history.shift();
                    }
                    
                    history.push({
                        id: Date.now(),
                        action: action,
                        details: details,
                        timestamp: now.toISOString()
                    });
                    
                    localStorage.setItem('syncHistory', JSON.stringify(history));
                } catch (error) {
                    console.error('记录同步历史失败:', error);
                }
            }
            
            // 显示同步历史
            function showSyncHistory() {
                try {
                    const history = JSON.parse(localStorage.getItem('syncHistory') || '[]');
                    
                    // 创建历史记录元素
                    const historyElement = document.createElement('div');
                    historyElement.className = 'space-y-3';
                    
                    if (history.length === 0) {
                        historyElement.innerHTML = `
                            <div class="text-center py-8 text-gray-500">
                                <i class="fa fa-history text-4xl mb-3 text-gray-300"></i>
                                <p>暂无同步历史记录</p>
                            </div>
                        `;
                    } else {
                        // 按时间倒序排列
                        const sortedHistory = history.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
                        
                        const historyList = document.createElement('div');
                        historyList.className = 'space-y-2 max-h-96 overflow-y-auto pr-2';
                        
                        sortedHistory.forEach(item => {
                            const date = new Date(item.timestamp);
                            const formattedDate = date.toLocaleString('zh-CN');
                            
                            const itemElement = document.createElement('div');
                            itemElement.className = 'p-3 bg-gray-50 rounded-lg border border-gray-200';
                            itemElement.innerHTML = `
                                <div class="flex justify-between items-start mb-1">
                                    <span class="font-medium text-primary">${item.action}</span>
                                    <span class="text-xs text-gray-500">${formattedDate}</span>
                                </div>
                                <p class="text-sm text-gray-600">${item.details}</p>
                            `;
                            
                            historyList.appendChild(itemElement);
                        });
                        
                        historyElement.appendChild(historyList);
                        
                        // 添加清除历史按钮
                        const clearButton = document.createElement('button');
                        clearButton.className = 'btn-secondary w-full mt-3';
                        clearButton.innerHTML = '<i class="fa fa-trash-alt mr-1"></i> 清除历史记录';
                        clearButton.addEventListener('click', () => {
                            if (confirm('确定要清除所有同步历史记录吗？')) {
                                localStorage.removeItem('syncHistory');
                                showModal('同步历史', document.createElement('div'));
                                showSyncHistory();
                                showToast('同步历史已清除', 'success');
                            }
                        });
                        
                        historyElement.appendChild(clearButton);
                    }
                    
                    // 显示同步历史对话框
                    showModal('同步历史记录', historyElement);
                } catch (error) {
                    console.error('显示同步历史失败:', error);
                    showToast('显示同步历史失败', 'error');
                }
            }
            
            // 执行数据同步
            async function performDataSync(syncData) {
                try {
                    showToast('正在同步数据...', 'info', 10000);
                    
                    // 获取同步选项
                    const syncProducts = localStorage.getItem('sync-products-toggle') !== 'false';
                    const syncOrders = localStorage.getItem('sync-orders-toggle') !== 'false';
                    
                    // 模拟数据同步过程
                    await new Promise(resolve => setTimeout(resolve, 1500));
                    
                    // 应用同步的数据
                    if (syncProducts && syncData.products && syncData.products.length > 0) {
                        if (window.dataStore && window.dataStore.products) {
                            // 合并商品数据
                            const existingProductIds = new Set(window.dataStore.products.map(p => p.id));
                            const newProducts = syncData.products.filter(p => !existingProductIds.has(p.id));
                            
                            if (newProducts.length > 0) {
                                window.dataStore.products.push(...newProducts);
                                // 更新本地存储
                                localStorage.setItem('products', JSON.stringify(window.dataStore.products));
                                // 重新渲染商品列表
                                renderProductList();
                            }
                        }
                    }
                    
                    if (syncOrders && syncData.orders && syncData.orders.length > 0) {
                        if (window.dataStore && window.dataStore.orders) {
                            // 合并订单数据
                            const existingOrderIds = new Set(window.dataStore.orders.map(o => o.id));
                            const newOrders = syncData.orders.filter(o => !existingOrderIds.has(o.id));
                            
                            if (newOrders.length > 0) {
                                window.dataStore.orders.push(...newOrders);
                                // 更新本地存储
                                localStorage.setItem('orders', JSON.stringify(window.dataStore.orders));
                            }
                        }
                    }
                    
                    // 保存同步状态
                    saveSyncStatus(true);
                    
                    // 记录同步历史
                    let syncDetails = `成功同步了${syncData.products?.length || 0}个商品`;
                    if (syncOrders) {
                        syncDetails += `和${syncData.orders?.length || 0}个订单`;
                    }
                    recordSyncHistory('数据同步', syncDetails);
                    
                    showToast('数据同步成功', 'success');
                } catch (error) {
                    console.error('数据同步失败:', error);
                    showToast('数据同步失败，请重试', 'error');
                    recordSyncHistory('同步失败', `错误: ${error.message}`);
                }
            }
            
            // 加载上次同步时间
            const lastSyncTime = localStorage.getItem('lastSyncTime');
            if (lastSyncTime) {
                document.getElementById('last-sync-time').textContent = `(上次同步: ${lastSyncTime})`;
            }
            
            // 初始页面渲染
            navigateTo('home');
            renderProductList();
        }

        // 暴露initApp函数到全局，以便模块脚本调用
        window.initApp = initApp;
        
        // 暴露一些函数到全局，以便在HTML中调用
        window.navigateTo = navigateTo;
        window.editProduct = editProduct;
        window.deleteProduct = deleteProduct;
        window.updateCartItem = updateCartItem;
        window.removeFromCart = removeFromCart;
        
        // 页面加载完成后初始化应用
        document.addEventListener('DOMContentLoaded', function() {
            initApp();
            
            // 直接在DOMContentLoaded中实现支付配置初始化逻辑
            function initializePaymentConfig() {
                if (!window.paymentManager) {
                    console.error('paymentManager未初始化');
                    return;
                }
                
                const config = window.paymentManager.getPaymentConfig();
                
                // 初始化微信配置
                if (config.wechat) {
                    if (document.getElementById('wechat-enabled')) {
                        document.getElementById('wechat-enabled').checked = config.wechat.enabled;
                    }
                    if (document.getElementById('wechat-image')) {
                        document.getElementById('wechat-image').value = config.wechat.image || '';
                    }
                    if (document.getElementById('wechat-link')) {
                        document.getElementById('wechat-link').value = config.wechat.link || '';
                    }
                    
                    if (config.wechat.image && document.getElementById('wechat-image-preview')) {
                        document.getElementById('wechat-image-preview').src = config.wechat.image;
                        document.getElementById('wechat-image-preview').style.display = 'block';
                    }
                }
                
                // 初始化支付宝配置
                if (config.alipay) {
                    if (document.getElementById('alipay-enabled')) {
                        document.getElementById('alipay-enabled').checked = config.alipay.enabled;
                    }
                    if (document.getElementById('alipay-image')) {
                        document.getElementById('alipay-image').value = config.alipay.image || '';
                    }
                    if (document.getElementById('alipay-link')) {
                        document.getElementById('alipay-link').value = config.alipay.link || '';
                    }
                    
                    if (config.alipay.image && document.getElementById('alipay-image-preview')) {
                        document.getElementById('alipay-image-preview').src = config.alipay.image;
                        document.getElementById('alipay-image-preview').style.display = 'block';
                    }
                }
            }
            
            // 延迟初始化支付配置，确保paymentManager已加载
            setTimeout(initializePaymentConfig, 300);
        });
    </script>
</body>
</html>